Sobes.tech
Middle

What are propagation levels in transactions?

sobes.tech AI

Answer from AI

Transaction propagation levels in Spring define how methods marked as transactional interact with each other when one calls another. The propagation level determines whether a new transaction should be created, joined, or not used at all.

Main propagation levels in Spring:

  • REQUIRED: Uses existing transaction if present; otherwise, creates a new one. This is the default level.
@Transactional(propagation = Propagation.REQUIRED)
public void methodA() { /* ... */ }
  • SUPPORTS: Uses existing transaction if present; if not, executes without a transaction.
@Transactional(propagation = Propagation.SUPPORTS)
public void methodB() { /* ... */ }
  • MANDATORY: Uses existing transaction; throws exception if none exists.
@Transactional(propagation = Propagation.MANDATORY)
public void methodC() { /* ... */ }
  • NEVER: Executes without a transaction; throws exception if a transaction exists.
@Transactional(propagation = Propagation.NEVER)
public void methodD() { /* ... */ }
  • NOT_SUPPORTED: Executes without a transaction; suspends any existing transaction.
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void methodE() { /* ... */ }
  • REQUIRES_NEW: Always creates a new, independent transaction; suspends existing one.
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void methodF() { /* ... */ }
  • NESTED: Uses existing transaction if present, creating a nested transaction (savepoint). If none exists, behaves like REQUIRED.
@Transactional(propagation = Propagation.NESTED)
public void methodG() { /* ... */ }

Choosing the right propagation level is crucial for proper transaction management and data integrity when transactional methods call each other.