java - Spring-Hibernate 事务只读传播

标签 java spring hibernate

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

假设我有这个代码:

@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/

相关文章:

java - 读取excel文件2010 apache poi忽略空单元格

java - org.w3c.dom.ls.LSException 由 : java. lang.NegativeArraySizeException 引起

java - 访问 AST 类时出错

java - 为什么 transaction.wasCommited() 返回 false?

java - 测试输出内容到文件

java - 绘画以筛选参数对象的位置

spring - 如何在 Spring Boot 中选择性地升级依赖项? (样例: Spring Data)

java - Hibernate 和 Spring 连接池默认值

java - 在 Hibernate 中映射枚举子类型

java - 对 hibernate 应用程序使用@Transactional 注释导致错误