Fundamentals of Spring Transaction Management
This article explains the core principles of Spring transaction management, covering basic JDBC transaction steps, declarative @Transactional usage, AOP proxy mechanisms (JDK dynamic proxy and CGLIB), transaction propagation attributes, isolation levels, nested transactions, and Spring Boot support, with practical code examples.
Fundamentals of Spring Transaction Management
Spring transactions rely on the underlying database's transaction support; without it, Spring cannot provide transactional behavior. For plain JDBC you would manually obtain a connection, set auto‑commit, execute CRUD operations, commit or roll back, and finally close the connection.
Obtain connection: Connection con = DriverManager.getConnection() Start transaction: con.setAutoCommit(false) Execute CRUD
Commit or roll back: con.commit() / con.rollback() Close connection: con.close() When using Spring's transaction management, steps 2 and 4 are handled automatically. Spring creates proxies for beans annotated with @Transactional, opening and closing transactions around the target method.
Spring Transaction Mechanism
All data‑access technologies expose a transaction API. Spring unifies them through the PlatformTransactionManager interface, with specific implementations for JDBC, JPA, Hibernate, etc.
Example bean definition:
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setDataSource(dataSource());
return transactionManager;
}Declarative Transactions
Annotate classes or methods with @Transactional (from org.springframework.transaction.annotation) to enable declarative transaction handling via AOP.
@Transactional
public void saveSomething(Long id, String name) {
// database operations
}AOP Proxy Implementations
JDK dynamic proxy – works on interfaces; private methods are not intercepted.
CGLIB proxy – creates a subclass; private methods are still not intercepted.
Java Dynamic Proxy
Implement InvocationHandler to define method‑interception logic.
Use Proxy.newProxyInstance with a class loader and interfaces to create the proxy class.
Obtain the proxy class constructor via reflection.
Instantiate the proxy, passing the handler to the constructor.
CGLIB Proxy
CGLIB (Code Generation Library) generates a subclass at runtime using ASM, allowing proxying of concrete classes without requiring interfaces.
Example Service with Transaction Propagation
@Service
public class PersonServiceImpl implements PersonService {
@Autowired
PersonRepository personRepository;
@Autowired
PersonService selfProxyPersonService; // inject self‑proxy for internal calls
@Transactional
public Person save(Person person) {
Person p = personRepository.save(person);
try {
// start a new independent transaction
selfProxyPersonService.delete();
} catch (Exception e) { e.printStackTrace(); }
try {
// use current transaction, will roll back whole tx on exception
selfProxyPersonService.save2(person);
} catch (Exception e) { e.printStackTrace(); }
personRepository.save(person);
return p;
}
@Transactional
public void save2(Person person) {
personRepository.save(person);
throw new RuntimeException();
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void delete() {
personRepository.delete(1L);
throw new RuntimeException();
}
}Transaction Propagation Attributes
Spring defines how nested transactions behave when multiple transactional methods are invoked:
PROPAGATION_REQUIRED (default): joins an existing transaction or creates a new one if none exists.
PROPAGATION_REQUIRES_NEW : suspends the current transaction and starts a brand‑new one.
PROPAGATION_SUPPORTS : runs within a transaction if one exists; otherwise executes non‑transactionally.
PROPAGATION_NESTED : creates a save‑point within the existing transaction, allowing independent rollback to that point.
Database Isolation Levels
Common phenomena:
Dirty read : a transaction reads uncommitted changes from another transaction.
Non‑repeatable read : repeated reads within a transaction return different data because another transaction modified it.
Phantom read : a transaction re‑executes a range query and sees newly inserted rows.
Higher isolation levels improve consistency but reduce concurrency. Most databases default to READ COMMITTED; MySQL InnoDB defaults to REPEATABLE READ.
Spring’s Isolation Level Support
Spring maps the standard isolation levels to the underlying database via the isolation attribute of @Transactional.
Nested Transactions
When a method with PROPAGATION_NESTED throws an exception, Spring rolls back to the save‑point created for that method while the outer transaction can decide to commit or roll back independently.
Example of Handling Nested Transaction
void methodA() {
try {
ServiceB.methodB(); // PROPAGATION_NESTED
} catch (SomeException) {
// execute alternative business logic
}
}Summary
For projects that require transaction handling, prefer using Spring's TransactionCallback API over raw annotations, and ensure a solid understanding of transaction propagation and isolation to avoid unexpected behavior.
Spring Boot Transaction Support
Spring Boot automatically configures annotation‑driven transaction management via TransactionAutoConfiguration.
Read‑Only Transactions
Annotating a method with @Transactional(readOnly = true) signals the underlying datasource that the transaction will not modify data, allowing potential performance optimizations while still respecting the default isolation and propagation settings.
When to Use Read‑Only Transactions
Single‑statement queries where consistency is already guaranteed by the database.
Multi‑statement reporting queries that must see a consistent snapshot of data.
References
http://www.codeceo.com/article/spring-transactions.html
http://www.cnblogs.com/fenglie/articles/4097759.html
https://www.zhihu.com/question/39074428/answer/88581202
http://blog.csdn.net/andyzhaojianhui/article/details/51984157
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
