Spring @Transactional方法 - 参与交易 [英] Spring @Transactional method - participating transaction

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

问题描述

在一个道具中我有2个@Transactional方法。



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



<然后会发生什么,如果



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



两种方法将在同一个交易中运行?

解决方案

Spring AOP中的代理



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

  @Transactional 
public void doSomeThing(){//调用此方法的目标是代理

doSomeThingElse(); //此方法以实际类为目标,而不是PROXY,
//因此事务注释无效
}

@Transactional
public void doSomeThingElse() {
}

您是从外部调用代理,但第二次方法调用是从代理对象内部,因此没有事务支持。很自然地,它们在同一个事务中运行,无论第二种方法中@Transactional注释的值是什么



所以如果你需要单独的事务,你必须致电

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

来自外部。



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



访问当前的AOP代理来自内部的对象



 公共类SimplePojo实现Pojo {

public void foo(){
//这个有用,但是......哇!
((Pojo)AopContext.currentProxy())。bar();
}

public void bar(){
//某些逻辑...
}
}


in one dao I have 2 @Transactional methods.

if i do not provide any explicit properties,

then what will happen, if

I run one method in the body of another?

Both methods will run within THE SAME ONE TRANSACTION?

解决方案

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(){
}

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();

from outside.

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

Accessing the Current AOP Proxy object from the inside

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天全站免登陆