简体   繁体   中英

flush session in the middle of transaction

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.

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM