嵌套事务用例中的外部事务看不到数据库中持久的更新(JPA、MySQL、Spring Framework 和 Hibernate)

发布于 2024-10-10 03:24:28 字数 517 浏览 0 评论 0原文

我有一个案例,事务启动后(在代码中)调用一个方法来启动新事务。当内部事务完成时,数据将持久保存在数据库中,但数据对外部事务不可见。

这是代码片段。

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

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

“doMoreStuff”方法更新数据库中的一些数据,之后“doSomething”方法需要查看更新的数据,但事实并非如此。例如,“doMoreStuff”将布尔值从 false 设置为 true 并保留它。 “doSomething”方法仍然只将值视为 false。

有什么建议吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

芯好空 2024-10-17 03:24:28

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

因此,我假设第二个(嵌套)事务必须(?)是到数据库的新连接 - 否则不可能在不影响“外部”事务的情况下回滚“嵌套”事务。

如果情况确实如此,那么您可能会受到 MySQL 的默认隔离级别的影响,即“可重复读取”,它不会让外部事务看到在此之后提交的任何数据。 > 该交易已开始。

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

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.

年华零落成诗 2024-10-17 03:24:28

嵌套事务 - 请使用 - Propagation.PROPAGATION_NESTED

Nested Transactions - Please use - Propagation.PROPAGATION_NESTED

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文