Sobes.tech
Junior — Middle

If a method annotated with @Transactional calls another method with the same annotation, what will be the number of transactions created?

sobes.tech AI

Answer from AI

If a method annotated with @Transactional calls another method with the same annotation within the same class, usually only one transaction is created. This is because Spring uses proxies to manage transactions, and a call to a method within the same class does not go through the proxy, so a new transaction is not created.

Thus, during an internal call, the transaction will be shared between both methods, and nested transactions will not be created by default.

Example:

@Service
public class MyService {

    @Transactional
    public void methodA() {
        // transaction starts here
        methodB(); // call within the class, no new transaction is created
    }

    @Transactional
    public void methodB() {
        // runs in the same transaction as methodA
    }
}

If you want methodB to run in a separate transaction, the call must go through a proxy, for example, via another bean or using ApplicationContext.