Master Spring Transactions: Programming vs Declarative Approaches Explained
This article provides a comprehensive guide to Spring transaction management, covering both programmatic (TransactionTemplate) and declarative (@Transactional) methods, explaining their principles, code examples, and how Spring abstracts underlying JDBC steps to simplify database transaction handling for backend developers.
Spring transactions are a frequent interview topic in large tech companies. This article explains both programmatic and declarative transaction management in Spring.
Programmatic Transaction
Programmatic transactions are defined in code, allowing precise control over transaction boundaries. Spring offers TransactionTemplate and PlatformTransactionManager, with TransactionTemplate recommended.
@Autowired
private TransactionTemplate transactionTemplate;
public void testTransaction() {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
try {
// ... business code
} catch (Exception e) {
transactionStatus.setRollbackOnly();
}
}
});
}Declarative Transaction
Declarative transactions use Spring AOP and the @Transactional annotation, requiring minimal code changes and keeping business logic free of transaction management code.
@Transactional
public void insert(String userName) {
this.jdbcTemplate.update("insert into t_user (name) values (?)", userName);
}The main advantage of declarative transactions is that business logic remains free of transaction‑management code.
Transaction Principles
Spring itself does not implement transactions; it relies on the underlying database’s transaction support. For plain JDBC, transaction steps include obtaining a connection, disabling auto‑commit, performing CRUD operations, committing or rolling back, and closing the connection.
Connection con = DriverManager.getConnection(...);
con.setAutoCommit(false);
// execute CRUD operations
con.commit(); // or con.rollback();
con.close();Spring abstracts these steps, allowing developers to focus on business logic while Spring handles the transaction lifecycle.
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.
Mike Chen's Internet Architecture
Over ten years of BAT architecture experience, shared generously!
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.
