Spring @Transactional method - participating transaction

前端 未结 3 1877
离开以前
离开以前 2020-12-10 18:23

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 an

相关标签:
3条回答
  • 2020-12-10 18:27

    The default value of the propagation attribute of @Transactional is REQUIRED, which means:

    Support a current transaction, create a new one if none exists.

    So yes - both methods will run in the same transaction.

    But one important advice: don't make your DAO transactional. The services should be transactional, not the DAO.

    0 讨论(0)
  • 2020-12-10 18:30

    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...
       }
    }
    
    0 讨论(0)
  • 2020-12-10 18:34

    Spring doc

    one note:

    In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.

    0 讨论(0)
提交回复
热议问题