Junior — Middle
What happens to a transaction if a call to another method of the same class, also annotated with @Transactional, occurs inside a method marked with @Transactional?
sobes.tech AI
Answer from AI
If a method annotated with @Transactional calls another method of the same class, also with @Transactional, the internal call will not be treated as a separate transaction.
This happens because Spring uses proxies to manage transactions, and calls to methods within the same class bypass the proxy, calling methods directly. As a result, the @Transactional annotation of the second method is ignored, and all logic is executed within a single transaction opened by the outer method.
If you want the inner method to run in a separate transaction, you usually invoke it through a proxy (for example, by injecting the bean itself) or move the method to a separate service.
Example:
@Service
public class MyService {
@Transactional
public void outerMethod() {
// transaction is open
innerMethod(); // direct call, @Transactional annotation is ignored
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void innerMethod() {
// a new transaction will not open on direct call
}
}