Sobes.tech
Senior

In which cases will the @Transactional annotation not work?

sobes.tech AI

Answer from AI

The @Transactional annotation in Spring will not work (the transaction will not be applied) in the following cases:

  1. Calling a method with @Transactional directly within the same class — Spring uses proxies to manage transactions, and calling a method within the same class does not go through the proxy, so the annotation is ignored.

  2. Method is not public — by default, Spring applies transactions only to public methods.

  3. Proxy configuration is not set up or disabled — if Spring has not created a proxy for the bean, the annotation will not work.

  4. Exceptions that do not trigger rollback — by default, transactions rollback only on unchecked exceptions (RuntimeException and Error). If the method throws a checked exception, the transaction will not rollback unless explicitly specified via rollbackFor.

  5. Transaction is already completed or absent — if the method is called outside a transaction context and no new transaction is configured to be created.

  6. Using @Transactional on interface methods without proper proxy configuration — this may cause the annotation not to work.

Example of an internal call problem:

@Service
public class MyService {

    @Transactional
    public void transactionalMethod() {
        // code
    }

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

For the transaction to work, the call must go from outside through the Spring proxy.

In which cases will the @Transactional annotation not… - sobes.tech