Sobes.tech
Senior

How does @Transactional work? What happens when a transactional method is called from within the same class?

sobes.tech AI

Answer from AI

The @Transactional annotation in Spring is used for managing transactions at the method or class level. When a method with this annotation is called, Spring creates a proxy that wraps the method call in a transaction: a transaction is started before the method executes, committed upon successful completion, and rolled back if an exception occurs.

However, if a transactional method is called from within the same class (for example, one method calls another method annotated with @Transactional), the proxy does not get triggered, and a transaction will not be created. This happens because the call is made directly, bypassing the proxy responsible for transaction management.

Example:

@Service
public class MyService {

    @Transactional
    public void methodA() {
        // a transaction will be created
    }

    public void methodB() {
        methodA(); // call within the class, transaction will not be created
    }
}

For the transaction to work, the call must go through the proxy, for example, from another bean or via self-injection.