flush session in the middle of transaction

2019-09-19 08:10发布

问题:

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.