Spring @Transactional 方法——参与事务 [英] Spring @Transactional method - participating transaction

查看:40
本文介绍了Spring @Transactional 方法——参与事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个 dao 中,我有 2 个 @Transactional 方法.

in one dao I have 2 @Transactional methods.

如果我没有提供任何明确的属性,

if i do not provide any explicit properties,

那么会发生什么,如果

我在另一个方法体中运行一个方法?

I run one method in the body of another?

两种方法都将在同一个事务中运行?

Both methods will run within THE SAME ONE TRANSACTION?

推荐答案

Spring AOP 中的代理

在使用 Transactional 时,您正在处理类的代理,因此在这种情况下:

Proxies in Spring AOP

When using Transactional, you're dealing with proxies of classes, so in this scenario:

@Transactional
public void doSomeThing(){ // calling this method targets a proxy

    doSomeThingElse(); // this method targets the actual class, not the PROXY,
                       // so the transactional annotation has no effect
}

@Transactional
public void doSomeThingElse(){
}

您从外部调用代理,但第二个方法调用是从代理对象内部进行的,因此没有事务支持.所以自然而然,它们运行在同一个事务中,不管第二种方法中@Transactional注解的值是什么

you are calling the proxy from outside, but the second method call is made from inside the proxied object and therefor has no transactional support. So naturally, they run in the same transaction, no matter what the values of the @Transactional annotation in the second method are

所以如果你需要单独的交易,你必须调用

so if you need separate transactions, you have to call

yourservice.doSomething();
yourservice.doSomethingElse();

从外面.

整个场景在Spring AOP > 理解 AOP 代理,包括这个解决方案":

The whole scenario is explained pretty well in the chapter Spring AOP > Understanding AOP proxies, including this "solution":

public class SimplePojo implements Pojo {

   public void foo() {
      // this works, but... gah!
      ((Pojo) AopContext.currentProxy()).bar();
   }

   public void bar() {
      // some logic...
   }
}

这篇关于Spring @Transactional 方法——参与事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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