@Transactional(propagation = Propagation.REQUIRES_NEW)
and Propagation.NESTED
are two different transaction propagation behaviors in Spring, and they handle nested method calls with transactions in fundamentally different ways.
Here’s a breakdown of the key differences:
Propagation.REQUIRES_NEW
- Creates an Independent Transaction: When a method with
@Transactional(propagation = Propagation.REQUIRES_NEW)
is called from an existing transaction, Spring suspends the current transaction and starts a completely new, independent physical transaction. - Independent Commit/Rollback: The new transaction has its own isolation scope and can be committed or rolled back entirely independently of the outer transaction.
- Outer Transaction is Unaffected: If the inner
REQUIRES_NEW
transaction fails and rolls back, the outer transaction is not affected (unless you explicitly catch the exception and mark the outer transaction for rollback). Conversely, if the outer transaction rolls back, the innerREQUIRES_NEW
transaction, if it already committed, remains committed. - Resource Management: Each
REQUIRES_NEW
transaction uses its own separate database connection. This can lead to connection pool exhaustion if not managed carefully, as a single thread may hold multiple open connections. - Use Case: This is useful for operations that you want to be completely isolated and succeed or fail regardless of the state of the parent transaction. A classic example is a logging or auditing operation that you want to persist even if the main business transaction fails.
Propagation.NESTED
- Creates a Savepoint:
Propagation.NESTED
works differently. When a method with this propagation level is called from an existing transaction, it doesn’t create a new, independent transaction. Instead, it creates a “savepoint” within the existing transaction. - Partial Rollback: If the nested transaction fails, Spring rolls back to the savepoint. This means that the work done within the nested method is undone, but the work done by the outer transaction before the nested method was called is preserved.
- Dependent on Outer Transaction: The nested transaction is a true sub-transaction of the outer transaction. It can only be committed if and when the outer transaction commits. If the outer transaction rolls back for any reason (even if the nested transaction succeeded), the entire transaction, including the nested part, is rolled back.
- Resource Management:
Propagation.NESTED
typically uses the same physical transaction and database connection as the outer transaction, which is why it relies on savepoints. It’s a more efficient approach in terms of resource usage thanREQUIRES_NEW
.