java - 理解 Spring 事务——当一个事务方法调用另一个事务方法时会发生什么?

标签 java spring transactions

只是为了了解 Spring 事务的工作原理,我想知道在以下情况下会发生什么,其中一个标记为 @Transactional 的方法调用另一个标记为 @Transactional 的方法。

假设配置使用所有默认设置。

@Service("myService")
@Transactional
public MyService{
   public void myServiceMethod(){
      myDAO.getSomeDBObjects();
   }
}

@Repository("myDAO")
@Transactional
public MyDAOWithUsesBeyondMyService{
   public void getSomeDBObjects(){...}
}

现在如果我输入 MyService.myServiceMethod() 它显然会启动一个事务。然后,在深入了解 myDAO.getSomeDBObjects() 会发生什么?交易已经存在这一事实会导致没有新的交易诞生,还是我在这里创建了两个交易?

关于 Propagation 的文档(引用如下)似乎涵盖了这一点,但我想验证我的理解,我的处女大脑一下子就理解了这么多。

Propagation: Typically, all code executed within a transaction scope will run in that transaction. However, you have the option of specifying the behavior in the event that a transactional method is executed when a transaction context already exists. For example, code can continue running in the existing transaction (the common case); or the existing transaction can be suspended and a new transaction created. Spring offers all of the transaction propagation options familiar from EJB CMT. To read about the semantics of transaction propagation in Spring, see Section 10.5.7, “Transaction propagation”.

最佳答案

两个答案:

a) 不要这样做。在服务层或 dao 层中使用 @Transactional,但不能同时使用(服务层是通常的选择,因为您可能希望每个服务方法一个事务)

b) 如果你这样做,会发生什么取决于 @Transactional 注释的 propagation 属性,并在本节中描述:10.5.7 Transaction propagation .基本上:PROPAGATION_REQUIRED 意味着相同的事务将用于两种方法,而 PROPAGATION_REQUIRES_NEW 开始一个新事务。

关于您的评论:

Of course I kept reading and realized that, as I'm using proxies, this second method won't be managed by the transactional proxy, thus it's like any other method call.

在您的情况下并非如此(仅当两种方法都在同一个类中时)。

如果一个bean有方法ab,并且a调用b,那么b 在实际方法上调用,而不是在代理上调用,因为它是从代理内部调用的(一个 bean 不知道它被代理到外部世界)。

proxy      bean  
a() -->    a()
            |
            V  
b() -->    b()

但是,在您的情况下,服务将具有注入(inject)的 dao 对象,该对象本身就是代理,因此您会遇到这样的情况:

           proxy      bean
service    a() -->    a()
                       |
             /---------/
             |                 
             V
dao        b() -->    b()

关于java - 理解 Spring 事务——当一个事务方法调用另一个事务方法时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4171605/

相关文章:

spring - 在基于 tomcat Spring 的应用程序中使用 c3p0 连接池

java - 在 Spring Boot 中读取环境变量

php - 打开数据库记录时,不允许其他用户更改记录(PHP+MySQL)

java - 使用 eclipse 将表单数据发布到 php 服务器时如何获得正确的响应?

java - 如何在 JOptionPane.showMessageDialog 上关闭?

java - 是否可以在不创建b​​ean的情况下使用Spring AOP?

java - Spring事务和 hibernate : lazy initialization

php - MongoDB 4.0 中使用 PHP 的事务示例

sql-server - Sql Server更新命令丢失更新异常

java - colorAnimation 中无法访问的语句