Sobes.tech
Junior — Middle

What will happen to transactions in Spring if a method that is not marked as transactional calls a method with transactional settings inside it?

sobes.tech AI

Answer from AI

If a method that is not marked as transactional calls a method annotated with @Transactional, then by default, a transaction will be created and applied to the called method. Spring will open a new transaction when entering the transactional method and close it upon exit.

However, it is important to remember that if the transactional method is called within the same class via an internal call (this.method()), then Spring's proxy will not be triggered, and the transaction will not be applied.

Example:

@Service
public class MyService {

    public void nonTransactionalMethod() {
        transactionalMethod(); // Internal call, @Transactional may not work
    }

    @Transactional
    public void transactionalMethod() {
        // Transaction should be here
    }
}

In this case, the transaction will not be created. To ensure the transaction works, the call should go from outside through the Spring proxy.

What will happen to transactions in Spring if a… - sobes.tech