Spring Boot & Microservices (50 Qs)•Part 2: Persistence, Transactions & Security (11 - 24)
How does `@Transactional` propagation work (`REQUIRED` vs `REQUIRES_NEW`)?
mid LevelCode ExampleState ManagementSecurity & AuthDatabases & SQL
In Simple Words:
REQUIRED (Default): Joins the existing transaction if one exists; creates a new one if none exists. If the inner method throws an exception, the entire outer transaction rolls back.REQUIRES_NEW: Suspends the existing outer transaction and always starts an independent, new physical transaction. If the inner transaction fails, it rolls back without failing the outer transaction (unless the exception is propagated). Perfect for audit logging.
java
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void writeAuditLog(String action) {
auditRepository.save(new AuditEntry(action)); // Committed even if calling business transaction fails
}