flush session in the middle of transaction

﹥>﹥吖頭↗ 提交于 2019-12-12 02:25:24

问题


Stack : spring and hibernate.

service method looks like below,

@Transaction (readonly=false)

public void doSomething(){

    step1: fetch object1,

    step2: modify list from object1 (i.e object1.getListObject2()),

    step3: fetch object3,

    step4: do some more processing,

}

I noticed that session is flushed in step3. Not able to understand why session has to be flushed in the middle of transaction.


回答1:


It most certainly needs to be flushed in order for the query executed at step 3 to retrieve the correct values, taking into account the changes made in step 2.

Let's take a trivial example:

List<Bike> bikes = findAllBikes();
bikes.forEach(bike -> bike.setColor("red"));
List<Bike> blueBikes = findAllBlueBikes();
// blueBikes should be an empty list, right?

If Hibernate didn't flush before executing findAllBlueBikes(), it would execute the query against database rows that still contain blue bikes, since the changes made on the line before (i.e. making all the bikes red) wouldn't have been flushed yet. The query would thus return a non-empty list of bikes, although they're supposed to be all red.

And worse: since Hibernate would find the bikes in its first-level cache, the query for blue bikes would return bikes that are, actually, red.



来源:https://stackoverflow.com/questions/33979644/flush-session-in-the-middle-of-transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!