嵌套事务用例中的外部事务没有看到数据库中持久化的更新(JPA、MySQL、Spring 框架和 Hibernate) [英] Outer transaction in a nested transaction use case isn't seeing updates persisted in database (JPA, MySQL, Spring Framework, and Hibernate)

查看:59
本文介绍了嵌套事务用例中的外部事务没有看到数据库中持久化的更新(JPA、MySQL、Spring 框架和 Hibernate)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个案例,其中开始了一个事务,并且在此过程中(在代码中)调用了一个方法来启动一个新事务.内层事务完成后,数据会持久化到数据库中,但数据在外层事务中是不可见的.

这是代码片段..

@Transactional(readOnly = true)公共无效doSomething(){//这里发生了一些事情doMoreStuff();//这里发生了更多的事情.}@Transactional(传播 = 传播.REQUIRES_NEW)公共无效 doMoreStuff() {...}

doMoreStuff"方法更新数据库中的一些数据,之后doSomething"方法需要查看更新的数据,但事实并非如此.例如,doMoreStuff"正在将布尔值从 false 设置为 true 并将其持久化.doSomething" 方法仍然只看到值为 false.

有什么建议吗?

解决方案

我不知道 Hibernate 中的事务嵌套"是如何完成的(因为我不相信 MySQL 实际上可以嵌套事务).

所以我会假设第二个(嵌套)事务必须(?)是到数据库的新连接 - 否则不可能在不影响外部"事务的情况下回滚嵌套"事务.

如果确实如此,那么您可能会遇到 MySQL 的默认隔离级别,即 REPEATABLE READ 这不会让外部事务看到任何已提交的数据 那个交易开始了.

要测试这个理论,请尝试将(外部事务的)隔离级别更改为 READ COMMITTED,看看是否能解决问题.

I have a case where a transaction is started and along the way (in the code) a method gets called that starts a new transaction. When the inner transaction completes, the data is persisted in the database, but the data is not visible from the outer transaction.

Here's the code snippet(s)..

@Transactional(readOnly = true)
public void doSomething() {
    // Some stuff happens here
    doMoreStuff();
    // Some more stuff happens here.
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void doMoreStuff() {
    ...
}

The "doMoreStuff" method updates some data in the database, afterwards the "doSomething" method needs to see that updated data, but it's not. For example, "doMoreStuff" is setting a boolean from false to true and persisting it. The "doSomething" method is still only seeing the value as being false.

Any suggestions?

解决方案

I don't know how the transaction "nesting" is done in Hibernate (as I don't believe MySQL can actually nest transactions).

So I would assume that the second (nested) transaction must (?) be a new connection to the database - otherwise it wouldn't be possible to rollback the "nested" transaction without affecting the "outer" transaction.

If this is indeed the case, then you are probably hit by MySQL's default isolation level which is REPEATABLE READ which won't let the outer transaction see any data that has been committed after that transaction started.

To test this theory, try changing the isolation level (of the outer transaction) to READ COMMITTED and see if that solves the problem.

这篇关于嵌套事务用例中的外部事务没有看到数据库中持久化的更新(JPA、MySQL、Spring 框架和 Hibernate)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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