gpt4 book ai didi

java - Spring-Hibernate 事务只读传播

转载 作者:行者123 更新时间:2023-11-30 06:55:29 28 4
gpt4 key购买 nike

我阅读了有关事务传播和只读的内容。
但有一点我不太清楚。

假设我有这个代码:

@Transactional(readOnly = true)
public void first() {
second();
}

@Transactional
public void second() {
//do Something
}

会发生什么?
第一个方法是否会被挂起,因为它无法刷新/提交,而第二个方法需要它?
或者也许“只读”也传播到内部调用? (因为我处于“必需”传播模式)?

最佳答案

有一个名为 progagation 的功能,您可以在 @Transactional 注释上定义它。

有两个选项可以适合内部事务场景

嵌套:

Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else. There is no analogous feature in EJB. Note: Actual creation of a nested transaction will only work on specific transaction managers. Out of the box, this only applies to the JDBC DataSourceTransactionManager when working on a JDBC 3.0 driver. Some JTA providers might support nested transactions as well.

REQUIRES_NEW

PROPAGATION_REQUIRES_NEW starts a new, independent "inner" transaction for the given scope. This transaction will be committed or rolled back completely independent from the outer transaction, having its own isolation scope, its own set of locks, etc. The outer transaction will get suspended at the beginning of the inner one, and resumed once the inner one has completed.

由于外部事务被标记为readOnly,因此NESTED选项没有意义,因为内部事务的提交依赖于外部事务。外部不允许进行任何更改..

所以我认为只有

@Transaction(propagation = Propagation.REQUIRES_NEW)
public void second(..)

在这种情况下是有意义的。

只是强调一下..这在理论上应该可行..有很多因素需要考虑..数据库功能、库版本等..你必须做一些进一步的测试,但希望这能给你一个想法。

更新

要绕过这个..尝试创建另一个..更高级别的服务,该服务不会是事务性的..然后您可以注入(inject)较低级别的服务并按顺序执行调用,而不会出现嵌套事务问题:

    @Service
public class FacadeService{

@Autowired
private TransactionalService service;

public void perform(..){

service.first();
service.second();
...
}
}

关于java - Spring-Hibernate 事务只读传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41921163/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com