Transaction Management Part 2
Nested transactions, programmatic transaction management, TransactionTemplate
- Use REQUIRES_NEW and NESTED propagation levels
- Control transactions programmatically with TransactionTemplate
- Handle partial rollbacks with savepoints
Transaction Manager Hierarchy Declarative vs Programmatic Transaction Propagation
@Transactional annotation, how the framework invokes an interceptor, and what that interceptor does internally.
This guide assumes familiarity with @Transactional, AOP proxies, and basic Spring Bean configuration.Table of Contents
- Transaction Manager Hierarchy
- Types of Transaction Management
- Declarative Transaction Management
- Programmatic Transaction Management
- Transaction Propagation
- Passing Propagation — Declarative vs Programmatic
- Summary & Quick Reference
- Interview Notes
- Practice Questions
1. Transaction Manager Hierarchy
Overview
Spring Boot abstracts transaction management through a clean interface hierarchy. Regardless of whether you use JDBC, JPA, Hibernate, or a NoSQL driver, all transaction managers follow the same contract defined at the top of this hierarchy.
Understanding this hierarchy is critical because:
- It explains how
@Transactionalworks under the hood. - It lets you switch or explicitly configure the right transaction manager.
- It is a common interview topic.
The Four Layers
1Layer 1 ──► TransactionManager (Interface — empty marker)2 │3Layer 2 ──► PlatformTransactionManager (Interface — 3 key methods)4 │5Layer 3 ──► AbstractPlatformTransactionManager (Abstract Class — default implementation)6 │7Layer 4 ──► Concrete Implementations8 ├── DataSourceTransactionManager (JDBC)9 ├── JpaTransactionManager (JPA)10 ├── HibernateTransactionManager (Hibernate)11 └── JtaTransactionManager (Distributed Transactions)Layer 1 `TransactionManager` (Marker Interface)
1public interface TransactionManager {2 // Empty — marker interface only3}- This is the topmost interface in the hierarchy.
- It is a marker interface — it contains no methods.
- Its purpose is purely to mark a class as a "transaction manager" so Spring's context can identify and wire it correctly.
Layer 2 `PlatformTransactionManager` (Core Interface)
1public interface PlatformTransactionManager extends TransactionManager {2
3 TransactionStatus getTransaction(TransactionDefinition definition)4 throws TransactionException;5
6 void commit(TransactionStatus status) throws TransactionException;7
8 void rollback(TransactionStatus status) throws TransactionException;9}This interface defines the three fundamental operations of any transaction:
| Method | Purpose |
|---|---|
getTransaction() | Begin or retrieve an existing transaction |
commit() | Persist all changes made within the transaction |
rollback() | Undo all changes made within the transaction |
TransactionInterceptor (the AOP interceptor triggered by @Transactional) uses exactly these three methods internally:
- It calls getTransaction() to start the transaction.
- On success, it calls commit().
- On exception (inside the catch block), it calls rollback().Because PlatformTransactionManager is an interface, something must implement it. That's where Layer 3 comes in.
Layer 3 `AbstractPlatformTransactionManager` (Abstract Class)
1public abstract class AbstractPlatformTransactionManager2 implements PlatformTransactionManager {3
4 // Provides DEFAULT implementations of getTransaction, commit, rollback5 // Concrete subclasses override only what's specific to their technology6}- This abstract class provides a default, reusable implementation for
getTransaction,commit, androllback. - The logic for most transaction managers (begin, commit, rollback) is largely the same regardless of the underlying technology.
- Concrete implementations (Layer 4) extend this class and override only the parts specific to their database driver or ORM.
Layer 4 Concrete Transaction Managers
These are the actual implementations that know how to talk to a specific database technology:
| Implementation | Used With | Notes |
|---|---|---|
DataSourceTransactionManager | Plain JDBC | You write raw SQL queries manually |
JpaTransactionManager | JPA (Java Persistence API) | Entities mapped to tables; most CRUD auto-generated |
HibernateTransactionManager | Hibernate | Hibernate-specific ORM framework |
JtaTransactionManager | Distributed Transactions | Used with Two-Phase Commit across multiple DBs |
INSERT INTO ..., SELECT FROM ... manually.
- With JPA, you create entity classes annotated with @Entity, and Spring Data generates most queries for you. JpaRepository methods like save(), findById() require no SQL.
- Hibernate is a popular JPA implementation — it is* JPA-compliant but has its own additional features.Hierarchy Diagram
2. Types of Transaction Management
Spring Boot provides two approaches to transaction management:
| Declarative | Programmatic | |
|---|---|---|
| How | Annotations (@Transactional) | Manual code (API calls) |
| Spring hides boilerplate? | ✅ Yes | ❌ No |
| Flexibility | Lower | Higher |
| Maintainability | High | Lower (repetitive code) |
| Use case | Most standard cases | Fine-grained control needed |
3. Declarative Transaction Management
Overview
Declarative transaction management means you declare your transactional intent using an annotation — @Transactional — and Spring Boot handles all the wiring behind the scenes.
1@Transactional2public void updateUser(User user) {3 // business logic4}When Spring Boot sees @Transactional, it:
- Creates an AOP proxy around the method.
- The
TransactionInterceptorintercepts the call. - Internally calls
getTransaction(), runs your method, thencommit()orrollback().
@Transactional without any configuration, Spring Boot automatically selects the appropriate transaction manager based on what's on the classpath. In most Spring Boot + JPA projects, it will choose JpaTransactionManager.Explicitly Specifying a Transaction Manager
Sometimes you need to override the auto-selected manager — for example, if you want to use raw JDBC instead of JPA.
Step 1: Create a configuration class and declare a bean.
1@Configuration2public class AppConfig {3
4 @Bean5 public PlatformTransactionManager userTransactionManager(DataSource dataSource) {6 // Explicitly using DataSourceTransactionManager (JDBC-based)7 return new DataSourceTransactionManager(dataSource);8 }9}Step 2: Reference the bean name in @Transactional.
1@Transactional(transactionManager = "userTransactionManager")2public void updateUser(User user) {3 // Spring will find the bean named "userTransactionManager"4 // and use DataSourceTransactionManager for this method5}@Bean method is used as the bean name. So userTransactionManager() creates a bean named "userTransactionManager".
If you want a different name, use: @Bean(name = "customName").4. Programmatic Transaction Management
Overview
Programmatic transaction management means you write the transaction logic yourself in code — calling getTransaction(), commit(), and rollback() explicitly.
When to use programmatic over declarative?
Consider this method:
1public void updateUser(User user) {2 updateDB_initialOperations(user); // Step 1: DB operations3 callExternalAPI(user); // Step 2: External API call (slow!)4 updateDB_finalOperations(user); // Step 3: DB operations5}If you put @Transactional on updateUser():
- The database connection is held open for the entire duration.
- The external API call (Step 2) might take 3–4 seconds.
- During peak traffic, holding DB connections while waiting for an external API becomes a serious bottleneck — it can choke your system.
Programmatic approach lets you wrap only the DB operations in transactions and exclude the external API call from the transaction scope.
Approach 1 Manual API (`PlatformTransactionManager` directly)
1@Service2public class UserService {3
4 private final PlatformTransactionManager transactionManager;5
6 // Constructor injection7 public UserService(PlatformTransactionManager transactionManager) {8 this.transactionManager = transactionManager;9 }10
11 public void updateUserProgrammatic(User user) {12 // Step 1: Begin the transaction13 TransactionStatus status = transactionManager.getTransaction(null);14
15 try {16 // Step 2: Execute your business logic17 updateDB_initialOperations(user);18 // external API call can go here — OUTSIDE the transaction19 updateDB_finalOperations(user);20
21 // Step 3: Commit on success22 transactionManager.commit(status);23
24 } catch (Exception e) {25 // Step 4: Rollback on failure26 transactionManager.rollback(status);27 throw e;28 }29 }30}Supporting AppConfig:
1@Configuration2public class AppConfig {3
4 @Bean5 public PlatformTransactionManager userTransactionManager(DataSource dataSource) {6 return new DataSourceTransactionManager(dataSource);7 }8}◆ Line-by-Line Explanation
| Line | Explanation |
|---|---|
transactionManager.getTransaction(null) | Starts a new transaction. null means use default TransactionDefinition settings. Returns a TransactionStatus token. |
updateDB_initialOperations(user) | Your actual DB write operations run inside the active transaction. |
transactionManager.commit(status) | If no exception, all changes are permanently saved. |
transactionManager.rollback(status) | On any exception, all changes are undone. |
Approach 2 `TransactionTemplate` (Cleaner, Recommended)
TransactionTemplate is a wrapper/template provided by Spring that internally handles getTransaction(), commit(), and rollback(). You only provide your business logic as a callback.
AppConfig — create a TransactionTemplate bean:
1@Configuration2public class AppConfig {3
4 @Bean5 public PlatformTransactionManager userTransactionManager(DataSource dataSource) {6 return new DataSourceTransactionManager(dataSource);7 }8
9 @Bean10 public TransactionTemplate transactionTemplate(11 PlatformTransactionManager userTransactionManager) {12 return new TransactionTemplate(userTransactionManager);13 // You can also set propagation, name, etc. here (see Section 6)14 }15}Service class — use the template:
1@Service2public class UserService {3
4 private final TransactionTemplate transactionTemplate;5
6 public UserService(TransactionTemplate transactionTemplate) {7 this.transactionTemplate = transactionTemplate;8 }9
10 public void updateUserProgrammatic(User user) {11
12 // Pass your business logic as a lambda (TransactionCallback)13 transactionTemplate.execute(status -> {14 updateDB_initialOperations(user);15 updateDB_finalOperations(user);16 return null; // Return null if no result needed17 });18 }19}◆ How `TransactionTemplate.execute()` works internally
◆ Key Points about `TransactionTemplate`
execute()accepts aTransactionCallback— a functional interface with the methoddoInTransaction().- Because it's a functional interface, you can pass a lambda expression as the callback.
- The template handles
getTransaction, runs your callback, then handlescommitorrollback. - This is a cleaner approach compared to Approach 1 — less repetition, same power.
Comparison: Declarative vs Approach 1 vs Approach 2
5. Transaction Propagation
Overview
Propagation defines what happens when a @Transactional method is called from within another @Transactional method.
When the TransactionInterceptor calls getTransaction(), it first checks the propagation setting to decide:
- Should it join the existing transaction?
- Should it create a new one?
- Should it suspend the current one?
- Should it throw an exception?
The Core Scenario
1Method One ──► @Transactional → Transaction T1 created2 │3 └──► calls4 │5 Method Two ──► @Transactional → What happens here?When Method One starts, Transaction T1 is created. When Method One calls Method Two (which is also @Transactional), the interceptor fires again for Method Two. The propagation value determines whether Method Two:
- Joins T1
- Creates a new T2 (suspending T1)
- Runs without any transaction
- Throws an exception
@Transactional method is called from another @Transactional method?"
The answer is: It depends on the propagation setting.All Propagation Types
◆ `REQUIRED` (Default)
1@Transactional(propagation = Propagation.REQUIRED)2// Same as just: @TransactionalRule:
- If a parent transaction exists → join it (use the same transaction).
- If no parent transaction exists → create a new one.
Observed behavior:
- Method One creates Transaction T1.
- Method Two (with
REQUIRED) is called from Method One. - Method Two does NOT create a new transaction. It runs inside T1.
TransactionSynchronizationManager.getCurrentTransactionName()returns the same name (Method One's transaction name) when called inside Method Two.
1Method One [Transaction: T1]2 └──► Method Two [Transaction: T1] ← same transaction, no new one created◆ `REQUIRES_NEW`
1@Transactional(propagation = Propagation.REQUIRES_NEW)Rule:
- If a parent transaction exists → suspend it, create a new transaction for Method Two.
- Once Method Two's transaction commits or rolls back → resume the parent transaction.
- If no parent transaction exists → create a new one.
Observed behavior:
- Method One runs in T1.
- Method Two is called → T1 is suspended → T2 is created for Method Two.
getCurrentTransactionName()inside Method Two shows a different name from Method One.- After Method Two commits/rolls back → T1 resumes.
1Method One [Transaction: T1]2 └──► Method Two [Transaction: T2] ← new transaction, T1 suspended3 (T2 commits/rollbacks)4 └──► Method One resumes [Transaction: T1]◆ `SUPPORTS`
1@Transactional(propagation = Propagation.SUPPORTS)Rule:
- If a parent transaction exists → join it.
- If no parent transaction exists → execute without any transaction.
Use this for methods that can work with or without a transaction (e.g., read-only operations that don't strictly need transactional guarantees).
◆ `NOT_SUPPORTED`
1@Transactional(propagation = Propagation.NOT_SUPPORTED)Rule:
- If a parent transaction exists → suspend it, execute the method without any transaction, then resume the parent.
- If no parent transaction exists → execute without any transaction.
In other words: always run without a transaction, regardless of what the caller has.
◆ `MANDATORY`
1@Transactional(propagation = Propagation.MANDATORY)Rule:
- If a parent transaction exists → join it.
- If no parent transaction exists → throw an exception.
Use this when a method must always be called from within an active transaction. It never creates a new transaction on its own.
Example use case: An internal helper method that performs a critical DB operation and must always be part of a larger transaction.
◆ `NEVER`
1@Transactional(propagation = Propagation.NEVER)Rule:
- If a parent transaction exists → throw an exception.
- If no parent transaction exists → execute without any transaction.
Use this when a method must never run inside a transaction.
Propagation Summary Table
| Propagation | Parent Transaction Exists | No Parent Transaction |
|---|---|---|
REQUIRED (default) | Join existing | Create new |
REQUIRES_NEW | Suspend parent, create new | Create new |
SUPPORTS | Join existing | Run without transaction |
NOT_SUPPORTED | Suspend parent, run without transaction | Run without transaction |
MANDATORY | Join existing | Throw exception |
NEVER | Throw exception | Run without transaction |
Propagation Flowchart
How Spring Implements Propagation Internally
The propagation logic lives inside AbstractPlatformTransactionManager. When the TransactionInterceptor calls createTransactionIfNecessary(), which internally calls getTransaction(), the abstract class checks the propagation setting:
1// Simplified pseudocode inside AbstractPlatformTransactionManager2
3protected TransactionStatus handleExistingTransaction(4 TransactionDefinition definition, Object transaction) {5
6 if (definition.getPropagationBehavior() == PROPAGATION_NEVER) {7 throw new IllegalTransactionStateException("...");8 }9
10 if (definition.getPropagationBehavior() == PROPAGATION_NOT_SUPPORTED) {11 suspend(transaction);12 return prepareTransactionStatus(/* no transaction */);13 }14
15 if (definition.getPropagationBehavior() == PROPAGATION_REQUIRES_NEW) {16 SuspendedResourcesHolder suspendedResources = suspend(transaction);17 // start a new transaction18 return startTransaction(definition, transaction);19 }20
21 // REQUIRED, SUPPORTS, MANDATORY → join the existing transaction22 return prepareTransactionStatus(definition, transaction, false);23}AbstractPlatformTransactionManager class, specifically the getTransaction() method and the handleExistingTransaction() helper.6. Passing Propagation Declarative vs Programmatic
Declarative
Simply include the propagation attribute in @Transactional:
1@Transactional(propagation = Propagation.REQUIRES_NEW)2public void myMethod() {3 // This always runs in a brand-new transaction4}5
6@Transactional(propagation = Propagation.MANDATORY)7public void criticalHelper() {8 // Must be called from within an active transaction9}Programmatic Approach 1 (using `TransactionDefinition`)
Pass a TransactionDefinition object to getTransaction() instead of null:
1@Service2public class UserService {3
4 private final PlatformTransactionManager transactionManager;5
6 public UserService(PlatformTransactionManager transactionManager) {7 this.transactionManager = transactionManager;8 }9
10 public void updateUserProgrammatic(User user) {11
12 // Create a TransactionDefinition with custom settings13 DefaultTransactionDefinition definition = new DefaultTransactionDefinition();14 definition.setName("myCustomTransaction");15 definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);16
17 // Pass it to getTransaction()18 TransactionStatus status = transactionManager.getTransaction(definition);19
20 try {21 // Business logic22 updateDB(user);23
24 transactionManager.commit(status);25 } catch (Exception e) {26 transactionManager.rollback(status);27 throw e;28 }29 }30}null is passed to getTransaction(null), Spring uses default settings.
When a TransactionDefinition is passed, you control:
- Transaction name (useful for monitoring/logging)
- Propagation behavior
- Isolation level (covered in Part 3)
- Timeout
- Read-only flagProgrammatic Approach 2 (using `TransactionTemplate`)
Set propagation and name directly on the TransactionTemplate bean in AppConfig:
1@Configuration2public class AppConfig {3
4 @Bean5 public PlatformTransactionManager userTransactionManager(DataSource dataSource) {6 return new DataSourceTransactionManager(dataSource);7 }8
9 @Bean10 public TransactionTemplate transactionTemplate(11 PlatformTransactionManager userTransactionManager) {12
13 TransactionTemplate template = new TransactionTemplate(userTransactionManager);14
15 // Configure propagation and name here16 template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);17 template.setName("myTemplateTransaction");18
19 return template;20 }21}Then use it in your service exactly as shown in Approach 2 earlier:
1transactionTemplate.execute(status -> {2 updateDB(user);3 return null;4});7. Summary & Quick Reference
Transaction Manager Hierarchy
Key Bullets
TransactionManager→ empty marker interface (top of hierarchy).PlatformTransactionManager→ definesgetTransaction,commit,rollback.AbstractPlatformTransactionManager→ provides default implementations; concrete classes extend and override.- Concrete managers:
DataSourceTransactionManager,JpaTransactionManager,HibernateTransactionManager,JtaTransactionManager. - Declarative =
@Transactionalannotation; Spring hides boilerplate; auto-selects transaction manager. - Programmatic Approach 1 = Inject
PlatformTransactionManager, manually callgetTransaction,commit,rollback. - Programmatic Approach 2 = Inject
TransactionTemplate, pass business logic as a lambda toexecute(). - Propagation = rules for what happens when one
@Transactionalmethod calls another. REQUIRED= default; joins existing or creates new.REQUIRES_NEW= always creates new; suspends existing.SUPPORTS= joins existing or runs without.NOT_SUPPORTED= always runs without transaction; suspends existing.MANDATORY= must have existing; throws if none.NEVER= must NOT have existing; throws if one exists.
8. Interview Notes
Q1: What is the hierarchy of Spring's transaction managers?
TransactionManager(marker interface) →PlatformTransactionManager(3 methods) →AbstractPlatformTransactionManager(default impl) → Concrete classes (JpaTransactionManager, etc.)
Q2: What are the three core methods in PlatformTransactionManager?
getTransaction(),commit(),rollback()
Q3: What is the default propagation type in @Transactional?
PROPAGATION_REQUIRED
Q4: What happens when a @Transactional method calls another @Transactional method?
- Depends on propagation. Default (
REQUIRED) joins the existing transaction.REQUIRES_NEWsuspends the parent and creates a new one.
Q5: What is the difference between REQUIRES_NEW suspend and abort?
- Suspend = parent transaction is paused but alive; it resumes after the inner transaction finishes.
- Abort/Rollback = transaction is permanently undone.
Q6: When would you choose programmatic over declarative?
- When you need fine-grained control — e.g., excluding a slow external API call from the transaction scope to avoid holding DB connections too long.
Q7: What is TransactionTemplate and why is it better than direct PlatformTransactionManager usage?
TransactionTemplatewrapsgetTransaction,commit, androllbackinto a reusable template. You only provide the business logic as a callback (lambda). It reduces boilerplate and improves readability.
Q8: How does Spring Boot auto-select a transaction manager?
- Based on classpath detection. If Spring Data JPA is present,
JpaTransactionManageris used by default. You can override by declaring a@BeanofPlatformTransactionManager.
Q9: What is MANDATORY propagation used for?
- It enforces that a method must always be called from within an already-active transaction. It never creates a new transaction; instead throws
IllegalTransactionStateExceptionif no transaction exists.
Q10: What is JtaTransactionManager used for?
- For distributed transactions (spanning multiple databases or resource managers), often using the Two-Phase Commit protocol.
9. Practice Questions
Easy
- What are the three methods defined by
PlatformTransactionManager? - What propagation type does
@Transactionaluse by default? - What is the difference between declarative and programmatic transaction management?
- In
TransactionTemplate, what method do you call to execute your business logic? - If you want Spring Boot to use
DataSourceTransactionManagerinstead ofJpaTransactionManager, how do you configure it?
Medium
- Explain what happens, step-by-step, when Method A (
@Transactional) calls Method B (@Transactional(propagation = REQUIRES_NEW)). - Why is holding a DB connection during an external API call a problem? How does programmatic transaction management solve it?
- What is the difference between
SUPPORTSandNOT_SUPPORTEDpropagation? - How do you pass a custom transaction name and propagation in Approach 1 (direct
PlatformTransactionManagerusage)? - What is
AbstractPlatformTransactionManager's role in the hierarchy?
Hard
- Trace the execution flow from an HTTP request hitting a
@Transactionalservice method all the way to a database commit — mention all Spring components involved (TransactionInterceptor,PlatformTransactionManager,AbstractPlatformTransactionManager, concrete manager). - If you have 3 nested
@Transactionalmethods — outer usesREQUIRED, middle usesREQUIRES_NEW, inner usesMANDATORY— describe the transactions that exist at each stage. - What would happen if
MANDATORYis used on a method called directly from a non-@Transactionalcontroller endpoint? What exception is thrown? - Design a service method that uses programmatic transaction management (Approach 2) to: wrap only the DB operations in a transaction, while the external API call happens outside the transaction. Show the full code with
AppConfigand the service method. - What is the risk of using
REQUIRES_NEWinside a high-volume service? How might it affect connection pool exhaustion?
READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, and SERIALIZABLE, and how they control concurrent transaction behavior.Mastery check
How well can you recall this?
Finished this lesson?