Spring Trx
Spring Trx
Notes
1. Introduction to Transactions in Spring Boot
2. @Transactional Annotation
Basic Usage
Primary Annotation: @Transactional is the main annotation for transaction management
java
Example Implementation
java
@Autowired
private EmployeeRepository employeeRepo;
A - Atomicity
All or Nothing Principle: Either all operations succeed or all fail
C - Consistency
State Transition: Moves database from one consistent state to another
Constraint Validation: All database constraints must be satisfied
D - Durability
Persistent Storage: Committed changes are permanently saved
System Failure Recovery: Data survives system crashes and restarts
REQUIRED (Default)
Behavior: Join existing transaction or create new one
java
@Transactional(propagation = Propagation.REQUIRED)
public void methodWithRequired() {
// Business logic here
}
REQUIRES_NEW
Behavior: Always create a completely new transaction
Characteristics:
Suspends current transaction if exists
java
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void methodWithRequiresNew() {
// Runs in completely separate transaction
}
NESTED
Behavior: Uses savepoints for nested operations
Characteristics:
Creates savepoint if transaction exists
java
@Transactional(propagation = Propagation.NESTED)
public void methodWithNested() {
// Can rollback to savepoint if needed
}
MANDATORY
Behavior: Requires existing transaction, throws exception if none
Usage: When method must run within existing transaction context
Characteristics:
Never creates new transaction
@Transactional(propagation = Propagation.MANDATORY)
public void methodWithMandatory() {
// Must be called within existing transaction
}
NEVER
Behavior: Throws exception if transaction exists
Characteristics:
Prohibits transaction execution
java
@Transactional(propagation = Propagation.NEVER)
public void methodWithNever() {
// Must run without any transaction
}
NOT_SUPPORTED
Behavior: Suspends existing transaction and runs without transaction
Characteristics:
Suspends current transaction if exists
java
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void methodWithNotSupported() {
// Runs outside transaction context
}
SUPPORTS
Behavior: Flexible - works with or without transaction
Usage: When transaction is optional
Characteristics:
Joins existing transaction if available
Runs without transaction if none exists
java
@Transactional(propagation = Propagation.SUPPORTS)
public void methodWithSupports() {
// Works in any context
}
Overview
Purpose: Control degree of isolation between concurrent transactions
Trade-off: Balance between consistency and performance
Read Phenomena
Dirty Read
Non-Repeatable Read
Phantom Read
Isolation Levels
READ_UNCOMMITTED
Consistency: Lowest
Performance: High
Consistency: Moderate
REPEATABLE_READ
Consistency: High
Use Case: When consistent reads are important
SERIALIZABLE
Allows: None
Performance: Lowest
Consistency: Highest
Use Case: Critical financial or audit operations
Method Requirements
Visibility: Must be applied only to public methods
Invocation: Method must be called from outside the bean (external invocation)
Proxy Limitation: Internal method calls bypass proxy and ignore @Transactional
Best Practices
1. Service Layer: Apply transactions at service layer, not repository layer
2. Method Granularity: Keep transactional methods focused and small
java
@Transactional(
propagation = Propagation.REQUIRED,
isolation = Isolation.READ_COMMITTED,
timeout = 30,
readOnly = false,
rollbackFor = {Exception.class},
noRollbackFor = {BusinessException.class}
)
Performance Considerations
Connection Pooling: Transactions hold database connections
Lock Duration: Longer transactions increase lock contention
Rollback Behavior
Default: Rollback on unchecked exceptions (RuntimeException and Error)
Checked Exceptions: Do not trigger rollback by default
Transaction Synchronization
Before Commit: Execute code before transaction commits
Testing Transactions
@Transactional in Tests: Automatically rolls back after each test
@Rollback: Control rollback behavior in tests
Common Issues
1. Self-Invocation: Internal method calls bypass transaction proxy
2. Private Methods: @Transactional ignored on non-public methods
Debugging Tips
Enable Transaction Logging: Set appropriate log levels
Monitor Connection Pool: Watch for connection exhaustion