복붙노트

[SPRING] Hibernate는 원치 않는 update 문을 실행한다.

SPRING

Hibernate는 원치 않는 update 문을 실행한다.

실행할 원시 쿼리가 있습니다.

String sqlSelect =
"select r.id_roster as id, " +
                    "count(roster_cat.id_category), " +
            "       sum(case when roster_cat.id_category IN ( :categoryIds)                       then 1 else 0 end) as counter " +
            "from roster r " +
            "inner join roster_sa_categories roster_cat " +
                "on r.id_roster = roster_cat.id_roster " +
            "where r.day = :dayToLookFor " +
                "and r.id_shop = :idShop " +
            "group by r.id_roster " +
            "having count(roster_cat.id_category) = :nrCategories " +
                "and count(roster_cat.id_category) = counter" ;

    Query selectRostersQuery = entityManager.createNativeQuery(sqlSelect);

    selectRostersQuery.setParameter("categoryIds", Arrays.asList(categoryIds));
    selectRostersQuery.setParameter("dayToLookFor", day.toString());
    selectRostersQuery.setParameter("idShop", shopId);
    selectRostersQuery.setParameter("nrCategories", categoryIds.length);

    List<Integer> rosterIds =  new ArrayList<>();

    List<Object> result = (List<Object>) selectRostersQuery.getResultList();

어떤 이유로 Hibernate는 select를 실행하기 전에 업데이트를 수행하기를 선택하고 그것은 내 데이터를 정말로 방해하고있다.

     Hibernate: /* update domain.Roster */ update roster set day=?,     employee_count=?, interval_end=?, interval_start=?, id_shop=? where id_roster=?
     Hibernate: /* update Roster */ update roster set day=?, employee_count=?,  interval_end=?, interval_start=?, id_shop=? where id_roster=?
     Hibernate: /* dynamic native SQL query */ select r.id_roster as id,   count(roster_cat.id_category),sum(case when roster_cat.id_category IN ( ?) then 1 else 0 end) as counter from roster r inner join roster_sa_categories 
roster_cat on r.id_roster = roster_cat.id_roster where r.day = ? and r.id_shop = ? group by r.id_roster having count(roster_cat.id_category) = ? and count(roster_cat.id_category) = counter

어떤 도움을 주시면 감사하겠습니다.

해결법

  1. ==============================

    1.당신이 설명하는 것은 정확하게 Hibernate의 FlushMode.AUTO가 의미하는 것입니다.

    당신이 설명하는 것은 정확하게 Hibernate의 FlushMode.AUTO가 의미하는 것입니다.

    쿼리가 실행될 때 Persistence Context (1LC)의 모든 수정 사항은 쿼리를 실행하기 전에 자동으로 플러시되어 데이터베이스에서 반환 된 결과가 메모리 내 수정으로 캐싱 된 결과와 일치 함을 보장합니다.

    쿼리에서 업데이트를 볼 엔터티를 반환 할 경우 작업을 다시 평가해야합니다. 플러시 작업을 피하기 위해 업데이트 전에 쿼리가 실행되는지 확인해야합니다. Persistence Context에있는 엔티티의 볼륨.

    플러시 된 변경 사항이 해당 쿼리에서 반환되지 않는다고 확신하는 경우 플러시 모드를 수동으로 설정하여 쿼리가 항상 플러시되지 않도록 할 수 있습니다.

    Query query = session.createQuery( ... );
    query.setFlushMode( FlushMode.COMMIT );
    List results = query.list();
    

    그러나 커밋되지 않은 변경 사항을 쿼리가 읽지 않을 것이라는 확신이들 때, 많은 문제를 야기 할 수 있고 변경 사항이 부주의하게 응용 프로그램에서 손실되는 이유를 이해하기 위해 긴 디버그 세션으로 이어질 수 있기 때문에이 작업을 수행하십시오.

  2. from https://stackoverflow.com/questions/42543400/hibernate-runs-unwanted-update-statement by cc-by-sa and MIT license