Search code examples
springtransactionsspring-transactions

Don't cover a method in transaction that is running inside a transactional method


I've asked this question somewhere ,

Suppose i have a method A which is running in transaction by using @transactional , if there is a method B which is being called from that transactional method , by default this will also be running in the same transaction.

So , the question is what to do that B is not covered by the transaction, how to avoid the transaction for B.


Solution

  • Based on the comment that both the methods are in the same class (self invocation), following code could work.

     @Service
    public class TestService {
    
        @Autowired // Self autowiring
        TestService service;
    
        @Transactional
        public void methodA() {
            service.methodB();
        }
    
        @Transactional(propagation = Propagation.NOT_SUPPORTED)
        public void methodB() {
            //...
        }
    }
    

    An external call to the service.methodA() will initialize a transaction and a self invocation to service.methodB() will result in methodB() be also part of the same transaction even though it is annotated to not participate in the transaction. To work around this we are self-autowiring and calling methodB() on that instance. This will result in the transaction configuration for methodB() to be honoured.

    Following is the reason for self autowiring , documentation

    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) does not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.

    Reference : Propagation.NOT_SUPPORTED

    Execute non-transactionally, suspend the current transaction if one exists. Analogous to EJB transaction attribute of the same name.

    Please do read through the doc shared for the limitations with this propagation behavior. Hope this helps