事务中的刷新会话 [英] flush session in the middle of transaction

查看:70
本文介绍了事务中的刷新会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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,

}

我注意到在第3步中冲洗了会话. 无法理解为什么在事务中间必须刷新会话.

解决方案

考虑到在步骤2中所做的更改,最肯定需要刷新它,以便在步骤3执行的查询检索正确的值. /p>

让我们举个简单的例子:

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

如果Hibernate在执行findAllBlueBikes()之前没有刷新,它将对仍然包含蓝色自行车的数据库行执行查询,因为之前在行上所做的更改(即将所有自行车变为红色)脸红了.因此,该查询将返回非空的自行车列表,尽管它们本应全部为红色.

更糟糕的是:由于Hibernate会在一级缓存中找到这些自行车,因此对蓝色自行车的查询将返回实际上是红色的自行车.

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

这篇关于事务中的刷新会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆