Chapter 8 of 12
Course Progress0 of 12 completed (0%)

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.

Database Transactions & ACID Isolation LevelsSafeguard 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.UNDERSTANDDatabaseTransactionsFOLLOW THE FLOWACID IsolationLevelsAPPLY ITSafeguard financialdataDatabase Transactions & ACID Isolation LevelsSafeguard 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.UNDERSTANDDatabaseTransactionsFOLLOW THE FLOWACID IsolationLevelsAPPLY ITSafeguard financialdata

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;

}

}

}

Concept Check

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

public void outer() { this.innerTransactional(); // Proxy bypassed! }Silent transaction failure · zero rollback protection · dirty data persisted

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

Client → [AOP Proxy Interceptor: BEGIN TX] → targetMethod() → [COMMIT TX]Guaranteed transaction boundary · automated connection management

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:

Propagation.REQUIRED (Default)

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!

Propagation.REQUIRES_NEW

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()));
    }
}
Concept Check

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

Spring @Transactional(isolation=...)

Select Database Isolation Level:

Dirty ReadsPREVENTED
Non-Repeatable ReadsALLOWED (Vulnerable)
Phantom ReadsALLOWED (Vulnerable)

Concurrent Execution Timeline (T1 vs T2):

T1Initial read is $1000
Transaction 1 (T1):SELECT bal FROM account WHERE id = 1; (Reads $1000)
Transaction 2 (T2):Idle
T2T2 commits balance change
Transaction 1 (T1):Processing loan...
Transaction 2 (T2):UPDATE account SET bal = 2000; COMMIT;
T1 Re-readNON-REPEATABLE READ! Same query returned two different values in T1
Transaction 1 (T1):SELECT bal FROM account WHERE id = 1; (Reads $2000)
Transaction 2 (T2):Finished

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:

Fix Self-Invocation & Checked Exception Rollback
Java

🎯 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 method executeTransfer with @Transactional.
  • By default, Spring transactions only rollback on unchecked exceptions (RuntimeException and Error). 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:

Concept Check 1 of 2
1

What is an UnexpectedRollbackException in Spring, and what causes it?

Concept Check 2 of 2
2

What is a 'Dirty Read' in database concurrency?

8Recap

  • @Transactional relies on Spring AOP proxies. Direct internal method calls via this.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_NEW for 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:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us