@Servicepublic class TransferService { @Transactional public void transfer(Long from, Long to, BigDecimal amount) { accounts.debit(from, amount); accounts.credit(to, amount); } // commit on return; rollback on RuntimeException}
Attribute
Default
propagation
REQUIRED
isolation
DEFAULT (DB)
readOnly
false
timeout
-1 (none)
rollbackFor
RuntimeException + Error
2. Configuring Transaction Propagation
Propagation
Behavior
REQUIRED
Join existing or start new
REQUIRES_NEW
Suspend current, start new
SUPPORTS
Join if exists, else non-tx
NOT_SUPPORTED
Suspend if active
MANDATORY
Throws if no active tx
NEVER
Throws if tx active
NESTED
Savepoint within outer tx
3. Setting Transaction Isolation Levels
Level
Prevents
READ_UNCOMMITTED
Nothing
READ_COMMITTED
Dirty reads
REPEATABLE_READ
+ Non-repeatable reads
SERIALIZABLE
+ Phantom reads (slowest)
4. Configuring Transaction Timeout
Example: Transaction with timeout
@Transactional(timeout = 5) // secondspublic Report generate() { /* must finish in 5s */ }