简体   繁体   English

事务中间刷新会话

[英]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. 我注意到在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. 考虑到在步骤2中所做的更改,最肯定需要刷新它,以便在步骤3中执行查询以检索正确的值。

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. 如果Hibernate在执行findAllBlueBikes()之前没有刷新,它将对仍然包含蓝色自行车的数据库行执行查询,因为之前在行上所做的更改(即使所有自行车变为红色)尚未被刷新。 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. 更糟糕的是:由于Hibernate会在一级缓存中找到这些自行车,因此查询蓝色自行车会返回实际上是红色的自行车。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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