Sobes.tech
Senior

What is @Transactional in Spring and what happens if the first method calls the second, both marked @Transactional?

sobes.tech AI

Answer from AI

The @Transactional annotation in Spring indicates that a method should be executed within a transaction. If a transaction already exists, the method will run within its context; otherwise, a new one will be created.

If the first method calls the second, and both are annotated with @Transactional, the behavior depends on the propagation settings (default is REQUIRED):

  • The second method will execute within the same transaction as the first (a new transaction is not created).
  • If the first method rolls back the transaction, changes made in the second method will also be rolled back.

Important: if the call to the second method occurs within the same class via a regular call (without Spring proxy), the @Transactional annotation on the second method may not work, as Spring uses proxies to manage transactions.

Example:

@Transactional
public void firstMethod() {
    // operations
    secondMethod(); // call within the same class
}

@Transactional
public void secondMethod() {
    // operations
}

In this case, secondMethod will not have a separate transaction and will run within the firstMethod transaction.

If you want the second method to have a separate transaction, you can set propagation to REQUIRES_NEW.

What is @Transactional in Spring and what happens if… - sobes.tech