gpt4 book ai didi

java - Hibernate 运行不需要的更新语句

转载 作者:行者123 更新时间:2023-12-03 09:10:53 24 4
gpt4 key购买 nike

我有要运行的 native 查询:

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 选择在执行选择之前进行更新,这确实干扰了我的数据

     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

如有任何帮助,我们将不胜感激,谢谢

最佳答案

您所描述的正是 Hibernate 的 FlushMode.AUTO 所暗示的内容。

执行查询时持久性上下文 (1LC) 中的任何修改都将在执行查询之前自动刷新,从而保证数据库返回的结果与内存中修改缓存的结果相匹配。

如果查询要返回您正在查看更新的实体,那么您可能应该重新评估您的操作,确保在更新之前触发查询以避免刷新操作,这可能会非常严重昂贵,具体取决于持久性上下文中实体的数量。

如果您绝对确定相关查询不会返回您所看到的刷新更改,则您始终可以通过设置刷新模式来强制查询不导致刷新手动:

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

但仅当您确定查询不会读取未提交的更改时才执行此操作,因为这可能会导致很多问题并导致长时间的调试 session ,以了解应用程序为何无意中丢失更改。

关于java - Hibernate 运行不需要的更新语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42543400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com