Sobes.tech
Senior

In which cases will @Transactional not work?

sobes.tech AI

Answer from AI

The @Transactional annotation in Spring will not work in the following cases:

  • Self-invocation (calling a method within the same class): if a method annotated with @Transactional is called from another method of the same class, Spring's proxy will not intercept the call, and a transaction will not be created.
  • Non-public methods: by default, Spring creates proxies for public methods. If a method with @Transactional has private, protected, or package-private access, the transaction may not be applied.
  • Lack of proxy or incorrect configuration: if the Spring context is not configured to create proxies (for example, missing <tx:annotation-driven> or @EnableTransactionManagement), the annotation will not work.
  • Exceptions that do not trigger rollback: by default, transactions rollback only on unchecked exceptions (RuntimeException and Error). If a method throws a checked exception, the transaction will not rollback unless explicitly specified.
  • Method marked as final or class final: JDK-based proxies cannot proxy such methods.

Example of self-invocation where the transaction will not work:

@Service
public class MyService {

    @Transactional
    public void transactionalMethod() {
        // code within a transaction
    }

    public void nonTransactionalMethod() {
        transactionalMethod(); // call within the class — transaction will not be created
    }
}