Cheatsheet

Propagation and rollback

Key idea

Propagation decides what a `@Transactional` method does when it's called: join the current transaction (`REQUIRED`), open a new independent one (`REQUIRES_NEW`), create a savepoint (`NESTED`) or require that there is, or isn't, a transaction. `rollbackFor` and `noRollbackFor` change which exceptions roll back.

Diagram (UML)

ApplicationContextAthlete30BookingServiceAuditServiceLoyaltyServicetransaction #1transaction #2H2

Key pieces

  • REQUIRED (default): joins the existing one or creates one
  • REQUIRES_NEW: suspends the existing one and creates another; commits or rolls back on its own
  • NESTED: a savepoint inside the existing one; JDBC only (DataSourceTransactionManager)
  • SUPPORTS (joins if there is one), NOT_SUPPORTED (suspends it), MANDATORY (requires one), NEVER (forbids one)
  • rollbackFor/rollbackForClassName and noRollbackFor/noRollbackForClassName
  • UnexpectedRollbackException, IllegalTransactionStateException

AuditService.java

@Transactional(propagation = Propagation.REQUIRES_NEW) // suspend the caller's, run in a NEW one
public void logRequiresNew(String message) {
    jdbc.update("INSERT INTO audit (message) VALUES (?)", message);
}                                                       // commits here, whatever the caller does later

Remember for the exam

  • With REQUIRED, every method shares one physical transaction: if any of them marks it for rollback, everything is undone
  • With REQUIRES_NEW, the inner one commits before returning; even if the outer one fails later, the inner work stays
  • NESTED rolls back only to the savepoint; the outer one can carry on and commit
  • MANDATORY without a transaction and NEVER with one throw IllegalTransactionStateException
  • rollbackFor = Exception.class makes checked exceptions roll back too
  • Propagation needs the proxy as well: it only applies between different beans

Exam traps

  • Catching in the outer method the exception of an inner REQUIRED one doesn't save the transaction: it's already marked rollback-only and the commit throws UnexpectedRollbackException
  • this.requiresNewMethod() from the same class does not open a new transaction
  • REQUIRES_NEW uses another connection; with a small pool it can run out
  • NESTED with JPA (JpaTransactionManager) isn't supported by default

← Propagation and rollback · Run it