Java & Spring Boot Enterprise Mastery · Chapter 8 · ~15 min · Advanced
Database Transactions & ACID Isolation Levels
Safeguard financial data integrity with Spring's transaction infrastructure. Master the Spring AOP proxy boundary, avoid catastrophic self-invocation bugs, configure propagation behaviors (REQUIRED vs REQUIRES_NEW), and eliminate concurrency anomalies across ACID isolation levels.
- Understand Spring AOP proxy interception around @Transactional boundaries
- Avoid the common self-invocation bug that silently bypasses transactions
- Configure transaction propagation (REQUIRED vs REQUIRES_NEW)
- Analyze concurrency anomalies: dirty reads, non-repeatable reads, and phantom reads
Database Transactions & ACID Isolation Levels: learn it visually
Safeguard financial data integrity with Spring's transaction infrastructure. Master the Spring AOP proxy boundary, avoid catastrophic self-invocation bugs, configure propagation behaviors (REQUIRED vs REQUIRES_NEW), and eliminate concurrency anomalies across ACID isolation levels.
1The Spring AOP Proxy & The Self-Invocation Trap
Spring's @Transactional annotation is not magic; it relies on Spring AOP (Aspect-Oriented Programming) proxies. When a bean is injected into another class, Spring does not inject the raw Java object; it injects a dynamic CGLIB proxy wrapper around it:
// Conceptual Spring AOP Proxy Wrapper
public class OrderService$$SpringProxy extends OrderService {
public void placeOrder() {
TransactionStatus status = txManager.getTransaction(def);
try {
super.placeOrder(); // Invoke real method on target
txManager.commit(status); // Commit SQL transaction
} catch (RuntimeException | Error ex) {
txManager.rollback(status); // Rollback
throw ex;
}
}
}
Why does calling an internal @Transactional method via 'this.doWork()' fail to start a database transaction?
2Dual Mental Model: Direct Invocation vs Proxied Transactions
Compare direct method execution against Spring AOP proxy interception and rollback semantics:
Wrong idea: Internal self-invocation (this.innerMethod()) executing transactions
Calling an internal @Transactional method from another method in the same class; 'this' calls the raw Java object directly, completely bypassing Spring's AOP proxy.
Real system: Invocation through Spring AOP Proxy wrapper
Calls entering from outside the bean hit the dynamic CGLIB proxy, which opens a DB connection, begins transaction, invokes target, and commits or rolls back.
3Transaction Propagation: REQUIRED vs REQUIRES_NEW
When one transactional service method calls another transactional service method, Spring's Propagation setting determines whether they share the same physical database transaction or spawn an independent isolated transaction:
Join Existing Transaction
If an active transaction already exists, join it. If none exists, create a new one. Any rollback in the inner method marks the entire composite transaction as rollback-only!
Suspend & Create Independent TX
Always suspends any existing outer transaction and allocates an independent database connection for a brand-new transaction. Ideal for audit logging that must commit even if the parent business transaction aborts!
@Service
public class AuditLogService {
private final AuditRepository auditRepo;
public AuditLogService(AuditRepository auditRepo) {
this.auditRepo = auditRepo;
}
// REQUIRES_NEW: Must commit even if the outer business method throws an exception and rolls back!
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void recordSecurityAudit(String action, Long userId) {
auditRepo.save(new AuditLog(action, userId, Instant.now()));
}
}When should an enterprise architect use Propagation.REQUIRES_NEW instead of Propagation.REQUIRED?
4Interactive Visualizer: ACID Concurrency Anomaly Matrix
Simulate concurrent transactions T1 and T2 under different isolation levels to see how dirty reads, non-repeatable reads, and phantom reads manifest and are prevented:
ACID Isolation Levels & Concurrency Anomaly Matrix
Simulate concurrent transactions T1 and T2 to inspect dirty reads, non-repeatable reads, and phantom reads
Select Database Isolation Level:
Concurrent Execution Timeline (T1 vs T2):
5The Checked Exception Pitfall: rollbackFor = Exception.class
One of the oldest and most dangerous gotchas in Spring is that by default, @Transactional only rolls back on unchecked exceptions (RuntimeException and Error). If your method throws a checked exception (Exception, IOException, SQLException), Spring will silently COMMIT the transaction!
// ALWAYS specify rollbackFor = Exception.class in enterprise services!
@Transactional(
rollbackFor = Exception.class,
isolation = Isolation.READ_COMMITTED,
timeout = 10 // Aborts and rolls back if execution takes longer than 10 seconds
)
public void transferWithFullSafety(Long fromAccount, Long toAccount, BigDecimal amount) throws BankingException {
accountRepo.debit(fromAccount, amount);
externalSanctionCheck(fromAccount); // If throws checked BankingException -> SAFE ROLLBACK!
accountRepo.credit(toAccount, amount);
}6Code Bug Hunt: Silent Transaction Failure & Checked Exception
The BankingTransferService below suffers from two critical flaws: an internal self-invocation that bypasses the Spring AOP proxy, and a checked exception that silently commits partial funds transfers. Refactor it to ensure strict transactional integrity:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
- Spring declarative transactions rely on Spring AOP proxies. Invoking
this.transferFunds(...)bypasses the proxy, meaning no transaction is started. Annotate the entry-point methodexecuteTransferwith@Transactional. - By default, Spring transactions only rollback on unchecked exceptions (
RuntimeExceptionandError). When throwing checked exceptions (java.lang.Exception), specify:@Transactional(rollbackFor = Exception.class).
7Chapter Knowledge Challenge
Test your mastery of Spring transaction architecture and ACID isolation:
What is an UnexpectedRollbackException in Spring, and what causes it?
What is a 'Dirty Read' in database concurrency?
8Recap
@Transactionalrelies on Spring AOP proxies. Direct internal method calls viathis.method()bypass the proxy and fail to execute within a transaction.- Always declare
@Transactional(rollbackFor = Exception.class)to guarantee rollbacks on checked exceptions. - Use
Propagation.REQUIRES_NEWfor independent operations (like audit logging) that must commit even when the outer transaction rolls back. - Understand isolation levels: READ_COMMITTED prevents dirty reads; REPEATABLE_READ prevents non-repeatable reads using MVCC snapshots; SERIALIZABLE eliminates all anomalies.
Ready for Chapter 9? Mark this chapter as complete to proceed: