Video in progress

Strong Middle 🌱 Spring

How does Propagation.NESTED work, and how does it differ from REQUIRES_NEW?

NESTED doesn't open a new transaction: it sets a savepoint inside the open transaction, and if the inner part fails, only that part is rolled back to the savepoint. REQUIRES_NEW suspends the outer one and opens an independent transaction on a separate connection.

📖 Answer

The difference is easy to see from the connection and commit point of view:

NESTED REQUIRES_NEW
Connection the same one a second connection is taken
Does the inner part commit no, only together with the outer one yes, immediately, independently
If the inner part fails rollback to the savepoint, the outer one continues only the inner one rolls back
If the outer one rolls back the inner changes are lost too the inner changes are kept
Locks in one transaction two transactions can end up waiting for each other
@Transactional
public void importBatch(List<Row> rows) {
    for (Row r : rows) {
        try {
            rowImporter.importOne(r); // @Transactional(propagation = NESTED)
        } catch (InvalidRowException e) {
            errors.add(r); // only this row was rolled back
        }
    }
}

NESTED is exactly right here: the bad rows are skipped, but either the whole import commits or none of it does.

Limitations:

  • NESTED works fully only with DataSourceTransactionManager (a JDBC savepoint). JpaTransactionManager uses a JDBC savepoint too, but the Hibernate persistence context doesn't roll back to the savepoint, so entities in memory may stay in the old state. That's why use NESTED with JPA carefully, or not at all.
  • Most JTA managers don't support NESTED at all.

A task like writing an audit log, "keep it no matter what", is a job for REQUIRES_NEW.