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)
flowchart TB
call(["@Transactional method is called"]) --> q{"Is a transaction<br/>in progress?"}
q -- yes --> y1["REQUIRED / SUPPORTS / MANDATORY<br/>join it"]
q -- yes --> y2["REQUIRES_NEW<br/>suspend it, open a new one"]
q -- yes --> y3["NESTED<br/>savepoint inside it"]
q -- yes --> y4["NOT_SUPPORTED<br/>suspend it, run without"]
q -- yes --> y5["NEVER<br/>IllegalTransactionStateException"]
q -- no --> n1["REQUIRED / REQUIRES_NEW / NESTED<br/>open a new one"]
q -- no --> n2["SUPPORTS / NOT_SUPPORTED / NEVER<br/>run without"]
q -- no --> n3["MANDATORY<br/>IllegalTransactionStateException"]Key pieces
REQUIRED(default): joins the existing one or creates oneREQUIRES_NEW: suspends the existing one and creates another; commits or rolls back on its ownNESTED: 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/rollbackForClassNameandnoRollbackFor/noRollbackForClassNameUnexpectedRollbackException,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 laterRemember 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 NESTEDrolls back only to the savepoint; the outer one can carry on and commitMANDATORYwithout a transaction andNEVERwith one throwIllegalTransactionStateExceptionrollbackFor = Exception.classmakes 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
REQUIREDone doesn't save the transaction: it's already marked rollback-only and the commit throwsUnexpectedRollbackException this.requiresNewMethod()from the same class does not open a new transactionREQUIRES_NEWuses another connection; with a small pool it can run outNESTEDwith JPA (JpaTransactionManager) isn't supported by default