Sobes.tech
Senior

Why might a method with @Transactional not create a transaction?

sobes.tech AI

Answer from AI

A method annotated with @Transactional may not create a transaction for several reasons:

  • If the method is called directly within the same class (without proxy), Spring will not apply a transaction because transactions work through proxies.
  • If the Spring configuration does not include transaction support or the annotation is not recognized.
  • If the method is marked as private or final, the proxy cannot override it to create a transaction.
  • If there is already an active transaction and the current method is configured with propagation that does not create a new transaction.

Example of a problem with calling within a class:

@Service
public class MyService {
    @Transactional
    public void transactionalMethod() {
        // code
    }

    public void caller() {
        transactionalMethod(); // transaction will not be created if called within the same class
    }
}