Search code examples
javaspringspring-jdbcspring-transactions

When calling a spring Non-Transactional method from a Transactional Method in another instance, does the transaction get propagated?


Sorry if this has been discussed before, but I just could not find the answer in all the related discussions on @Transactional spring java annotation.

What happens if we call a method in another instance that does not have an @Transactional annotation from a method that has an @Transactional annotation? will the transaction from the @Transactaional annotated method be suspended? or would it be propagated?

I found a lot of discussions on if the call to the 2nd method is from the same instance, but not if the 2nd non-transactional method is in another instance. Thank you for your help!

Like in the example below, what would happen if methodb() in class B is called from methoda() in class A? Would the transaction from methoda be propagated or would methodb be non-transactional?

Example code below:

public class A {

  @Autowired
  B b;

  @Transactional
  public void methoda() {
    b.methodb();
  }
}



@Component
public class B {

  // this method is non transactional and is called from method A in class A
  public void methodb() {
    //do some db updates
  }
}

Solution

  • If there are no @Transactional annotations in B to tell it otherwise, then the b method uses the transaction established in the call to A.methoda. This is normal for Spring, we have components marked transactional that call DAOs that participate in the current transaction without being marked transactional themselves.

    If you really want to suspend the current transaction, you can add this annotation to the b method:

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    

    There is a caveat about suspending transactions in the Spring API doc:

    NOTE: Actual transaction suspension will not work out-of-the-box on all transaction managers. This in particular applies to JtaTransactionManager, which requires the javax.transaction.TransactionManager to be made available to it (which is server-specific in standard Java EE).