@Transactional
@Transactional propagation, rollback rules, readOnly flag, and common pitfalls
- Apply @Transactional and understand when a new transaction is created
- Configure rollbackFor and noRollbackFor rules
- Avoid the self-invocation proxy bypass pitfall
Course:
Spring Boot Series Instructor: Shreyansh Prerequisites: Spring Boot AOP, Concurrency Control Basics
Table of Contents
- Prerequisites
- Critical Section
- ACID Properties
- What Is a Transaction?
- The Problem Without Transactions
- The @Transactional Annotation
- Dependencies & Setup
- How @Transactional Works Internally (AOP)
- Practical Code Examples
- Transaction Lifecycle Flowchart
- Key Observations
- Common Mistakes
- Best Practices
- Interview Notes
- Topics Coming Next
- Summary
Prerequisites
Before studying @Transactional, you must understand two foundational concepts:
| Prerequisite | Why It Matters |
|---|---|
| Concurrency Control | Explains what happens when multiple threads/requests access shared resources simultaneously |
| Spring Boot AOP (Aspect-Oriented Programming) | @Transactional is implemented using AOP under the hood — without AOP knowledge, the internal workings will not make sense |
@Transactional annotation relies entirely on these AOP concepts to function.Critical Section
Overview
Before understanding transactions, you must understand the Critical Section — the core problem that transactions are designed to solve.
Definition
A Critical Section is a code segment where shared resources are being accessed and modified.
Real-World Analogy
Imagine a cab (taxi) in a ride-booking application.
- The cab has
ID: 1001 - Its current
status: AVAILABLE
This cab record in the database is a shared resource. Any code that reads and updates this record is a critical section.
The Problem Data Inconsistency
Consider 4 users trying to book the same cab in parallel:
1User 1 → reads cab 1001 → status = AVAILABLE → books it → "Car is booked!"2User 2 → reads cab 1001 → status = AVAILABLE → books it → "Car is booked!"3User 3 → reads cab 1001 → status = AVAILABLE → books it → "Car is booked!"4User 4 → reads cab 1001 → status = AVAILABLE → books it → "Car is booked!"All 4 users get a booking confirmation for the same cab! This is data inconsistency, and it happens because the critical section is not properly handled when multiple requests execute in parallel.
Solution
The solution is the proper use of Transactions, which provide the ACID properties to prevent such inconsistencies.
ACID Properties
Transactions guarantee the ACID properties — a set of four rules that ensure data integrity.
A Atomicity
Definition: In a transaction, if any single operation fails, the entire transaction is rolled back. All operations are treated as a single atomic unit — either all succeed or none do.
◆ Example
Suppose Account A has ₹10 and Account B has ₹20. A transaction transfers ₹5 from A to B:
| Step | Operation | Result |
|---|---|---|
| Operation 1 | Debit A by ₹5 | A = ₹5 ✅ |
| Operation 2 | Credit B by ₹5 | ❌ FAILED |
Without atomicity: A = ₹5, B = ₹20 → ₹5 has vanished from the system!
With atomicity: Operation 1 is also rolled back → A = ₹10, B = ₹20 → System is consistent again.
C Consistency
Definition: Before and after a transaction, the database must be in a consistent (valid) state. There must be no partially applied changes.
◆ Example
- Before Transaction: A = ₹10, B = ₹20 → Total = ₹30 ✅ (consistent)
- After Successful Transaction: A = ₹5, B = ₹25 → Total = ₹30 ✅ (consistent)
- After Failed + Rolled-Back Transaction: A = ₹10, B = ₹20 → Total = ₹30 ✅ (consistent)
- Inconsistent State (no rollback): A = ₹5, B = ₹20 → Total = ₹25 ❌ (₹5 missing!)
Atomicity leads to Consistency. They are directly linked.
I Isolation
Definition: Even if multiple transactions run in parallel, they must not interfere with each other. Each transaction behaves as though it is running in isolation, unaware of other concurrent transactions.
◆ How It Works Internally
Transactions use locking mechanisms to serialize access to shared data:
- Transaction 1 wants to update Account A → acquires a lock on A
- Transaction 2 also wants to update Account A → waits for the lock
- Once Transaction 1 releases the lock → Transaction 2 proceeds
D Durability
Definition: Once a transaction is committed, the data is permanently persisted. Even if the system crashes immediately after commit, the data must not be lost.
This is typically achieved through write-ahead logging (WAL) or similar mechanisms at the database level.
ACID Summary Table
| Property | Question It Answers | Guarantee |
|---|---|---|
| Atomicity | What if one operation fails? | All operations rollback |
| Consistency | Is the DB always valid? | DB state is always consistent |
| Isolation | Do parallel transactions interfere? | Each transaction runs independently |
| Durability | Is committed data safe? | Data persists even after crashes |
What Is a Transaction?
Definition
A Transaction is a sequence of database operations that are treated as a single unit of work. All operations in a transaction either succeed together (commit) or fail together (rollback).
Transaction Lifecycle
Manual Transaction Code (Without Spring Boot)
In raw Java/JDBC, you would write this manually for every database method:
1// Pseudocode — raw transaction management2connection.setAutoCommit(false); // BEGIN TRANSACTION3
4try {5 // Operation 1: Debit A6 debitFromA(connection, 5);7
8 // Operation 2: Credit B9 creditToB(connection, 5);10
11 connection.commit(); // ALL SUCCESS → COMMIT12} catch (Exception e) {13 connection.rollback(); // ANY FAILURE → ROLLBACK14} finally {15 connection.setAutoCommit(true); // END TRANSACTION16}The Problem With Manual Transaction Management
Imagine you have 1000 methods that touch the database:
1updateUser(...) // Touches DB2updateBulkUsers(...) // Touches DB3updateUserById(...) // Touches DB4updateUserByEmail(...) // Touches DB5// ... 996 more methodsEach of these needs the same boilerplate:
1BEGIN TRANSACTION2 // your actual business logic3IF all success → COMMIT4ELSE → ROLLBACK5END TRANSACTIONThis is:
- Duplicate code repeated in every single method
- Error-prone — easy to forget in one method
- Hard to maintain — if the pattern changes, you update 1000 places
- Pollutes business logic with infrastructure concerns
Your actual business logic is just this:
1debitFromA(5);2creditToB(5);Everything else is verbose boilerplate. This is exactly the problem @Transactional solves.
The `@Transactional` Annotation
Overview
@Transactional is a Spring Boot annotation that automatically manages transactions for you. By simply annotating a method (or class), Spring Boot handles begin, commit, and rollback — eliminating all the boilerplate.
Import
1import org.springframework.transaction.annotation.Transactional;@Transactional annotation from org.springframework.transaction.annotation.Transactional is the recommended one for Spring Boot applications. There is also javax.transaction.Transactional (JEE), but the Spring one provides more configuration options.Basic Syntax
1@Transactional2public void updateUser(User user) {3 // Your business logic only4 // Spring handles begin, commit, rollback automatically5 userRepository.save(user);6}Class-Level vs Method-Level
| Level | Syntax | Effect |
|---|---|---|
| Method Level | @Transactional on a method | Applies only to that specific method |
| Class Level | @Transactional on a class | Applies to all public methods in the class |
@Transactional is applied at the class level, it does NOT apply to private methods. Only public methods are intercepted by the AOP proxy.1// Class-level — all public methods get transaction management2@Transactional3@Service4public class UserService {5
6 public void updateUser(User user) { ... } // ✅ Transactional7 public void deleteUser(Long id) { ... } // ✅ Transactional8 private void helperMethod() { ... } // ❌ NOT Transactional9}1// Method-level — only annotated method gets transaction management2@Service3public class UserService {4
5 @Transactional6 public void updateUser(User user) { ... } // ✅ Transactional7
8 public void readUser(Long id) { ... } // ❌ NOT Transactional9}Dependencies & Setup
Required Dependencies (pom.xml)
◆ Dependency 1 Spring Data JPA (for relational databases)
1<dependency>2 <groupId>org.springframework.boot</groupId>3 <artifactId>spring-boot-starter-data-jpa</artifactId>4</dependency>@Transactional annotation for relational databases (MySQL, PostgreSQL, H2, etc.). If you are using a NoSQL database (MongoDB, Cassandra, etc.) that supports transactions, the dependency will differ — check the Spring Boot documentation for the correct starter.◆ Dependency 2 Database Driver
You must also include the driver for your specific database. Example for MySQL:
1<dependency>2 <groupId>com.mysql</groupId>3 <artifactId>mysql-connector-j</artifactId>4 <scope>runtime</scope>5</dependency>For H2 (in-memory, for testing):
1<dependency>2 <groupId>com.h2database</groupId>3 <artifactId>h2</artifactId>4 <scope>runtime</scope>5</dependency>application.properties Configuration
1spring.datasource.url=jdbc:mysql://localhost:3306/mydb2spring.datasource.username=root3spring.datasource.password=yourpassword4spring.jpa.hibernate.ddl-auto=update@Transactional.Optional @EnableTransactionManagement
In your main Spring Boot application class:
1@SpringBootApplication2@EnableTransactionManagement // Optional — Spring Boot auto-configures this3public class MyApplication {4 public static void main(String[] args) {5 SpringApplication.run(MyApplication.class, args);6 }7}@EnableTransactionManagement is optional in Spring Boot because Spring Boot's auto-configuration adds it automatically. However, it is good practice to add it explicitly so that:
- The intent is clear to other developers
- If auto-configuration fails for any reason, transactions will still work
Without @EnableTransactionManagement, methods annotated with @Transactional will be ignored and no transaction management will happen.How `@Transactional` Works Internally (AOP)
This is the most important section for deep understanding. Spring Boot's @Transactional is implemented using AOP (Aspect-Oriented Programming).
The Big Picture
Step-by-Step Internal Mechanism
◆ Step 1 Application Startup: Pointcut Expression Matching
When the Spring Boot application starts, the AOP framework scans all beans and looks for methods annotated with @Transactional. The Pointcut expression used internally looks something like:
1@within(org.springframework.transaction.annotation.Transactional)2// OR3@annotation(org.springframework.transaction.annotation.Transactional)This expression matches any class or method that carries the @Transactional annotation.
◆ Step 2 AOP Proxy Creation
Once a match is found, Spring wraps the bean in an AOP proxy. This proxy intercepts all calls to @Transactional methods.
◆ Step 3 The Advice: `TransactionInterceptor`
The Advice that runs is located inside the TransactionInterceptor class (which extends TransactionAspectSupport).
The key method is:
1// Inside TransactionInterceptor (Spring Framework source)2protected Object invokeWithinTransaction(Method method, Class<?> targetClass, 3 final InvocationCallback invocation) {4 // 1. Create / obtain a transaction5 TransactionInfo txInfo = createTransactionIfNecessary(...);6 7 Object retVal;8 try {9 // 2. Invoke YOUR method (the business logic)10 retVal = invocation.proceedWithInvocation();11 12 } catch (Throwable ex) {13 // 3. Exception occurred → ROLLBACK14 completeTransactionAfterThrowing(txInfo, ex);15 throw ex;16 } finally {17 cleanupTransactionInfo(txInfo);18 }19 20 // 4. No exception → COMMIT21 commitTransactionAfterReturning(txInfo);22 return retVal;23}This is the "magic" behind @Transactional — the begin/commit/rollback logic exists here. It is not magic; it is simply hidden from you in the Spring framework's code.
◆ Step 4 Advice Type: Around Advice
The advice used by @Transactional is Around Advice — the most powerful type of AOP advice. Around advice:
- Runs before the method → begins transaction
- Invokes the actual method → your business logic executes
- Runs after the method → commits or rolls back based on outcome
| Advice Type | When It Runs | Used by @Transactional? |
|---|---|---|
| Before | Before the method | ❌ No |
| After | After the method (always) | ❌ No |
| AfterReturning | After successful return | ❌ No |
| AfterThrowing | After exception | ❌ No |
| Around | Wraps the entire method | ✅ Yes |
Class Hierarchy
TransactionInterceptor extends TransactionAspectSupport. The invokeWithinTransaction method is defined in TransactionAspectSupport (the parent class) and called by TransactionInterceptor.
Practical Code Examples
Example 1 Basic @Transactional (Happy Path)
◆ Controller
1@RestController2@RequestMapping("/api")3public class UserController {4
5 @Autowired6 private UserService userService;7
8 @GetMapping("/update-user") // Should be @PostMapping in production9 public String updateUser() {10 userService.updateUser();11 return "User updated successfully";12 }13}◆ Service
1@Component2public class UserService {3
4 @Autowired5 private UserRepository userRepository;6
7 @Transactional8 public void updateUser() {9 // Your business logic only — no begin/commit/rollback needed10 User user = userRepository.findById(1L).orElseThrow();11 user.setName("Updated Name");12 userRepository.save(user);13
14 // No exception → Spring will COMMIT automatically15 }16}◆ What Happens Internally
11. HTTP GET /api/update-user22. UserController.updateUser() is called33. userService.updateUser() is called4 └── But actually: UserServiceProxy.updateUser() is called (AOP Proxy)54. TransactionInterceptor.invokeWithinTransaction() executes65. BEGIN TRANSACTION76. UserService.updateUser() (actual method) is invoked87. DB operations execute successfully98. No exception → COMMIT ✅109. Response returnedUser updated successfully
Console logs (with transaction logging enabled):
1Creating new transaction with name [com.example.UserService.updateUser]2Opened new EntityManager [SessionImpl] for JPA transaction3Committing JPA transaction on EntityManager [SessionImpl]Example 2 Exception Causes Rollback
◆ Service
1@Component2public class UserService {3
4 @Transactional5 public void updateUser() {6 // Some DB operation7 userRepository.save(someUser);8
9 // Simulating a failure10 throw new RuntimeException("Something went wrong!");11
12 // Code after this never executes13 // The save above will be ROLLED BACK14 }15}◆ What Happens Internally
11. HTTP GET /api/update-user22. TransactionInterceptor.invokeWithinTransaction() executes33. BEGIN TRANSACTION44. UserService.updateUser() invoked55. userRepository.save(someUser) executes66. RuntimeException thrown!77. TransactionInterceptor catches the exception88. completeTransactionAfterThrowing() called → ROLLBACK ↩️99. The save from step 5 is undone1010. Exception propagates to callerConsole logs:
1Creating new transaction with name [com.example.UserService.updateUser]2Opened new EntityManager [SessionImpl] for JPA transaction3Rolling back JPA transaction on EntityManager [SessionImpl]@Transactional only rolls back on unchecked exceptions (RuntimeException and its subclasses) and Errors. It does NOT roll back for checked exceptions unless explicitly configured with rollbackFor.
``java
// To rollback on checked exceptions too:
@Transactional(rollbackFor = Exception.class)
public void updateUser() throws Exception { ... }
``Example 3 Multiple Classes, No Duplicate Code
Without @Transactional, you'd write begin/commit/rollback in every method:
1// ❌ Without @Transactional — massive duplication2public class UserService {3 public void updateUser() {4 beginTransaction();5 try {6 // business logic7 commit();8 } catch (Exception e) {9 rollback();10 }11 }12}13
14public class EmployeeService {15 public void updateEmployee() {16 beginTransaction();17 try {18 // business logic19 commit();20 } catch (Exception e) {21 rollback();22 }23 }24}25
26public class OrderService {27 public void processOrder() {28 beginTransaction();29 try {30 // business logic31 commit();32 } catch (Exception e) {33 rollback();34 }35 }36}With @Transactional:
1// ✅ With @Transactional — clean, DRY code2@Service3public class UserService {4 @Transactional5 public void updateUser() {6 // Just your business logic7 }8}9
10@Service11public class EmployeeService {12 @Transactional13 public void updateEmployee() {14 // Just your business logic15 }16}17
18@Service19public class OrderService {20 @Transactional21 public void processOrder() {22 // Just your business logic23 }24}The boilerplate code exists once inside Spring's TransactionInterceptor — not in your code at all.
Transaction Lifecycle Flowchart
IOException, custom checked exceptions), the transaction will commit even though an exception was thrown.Key Observations
- @Transactional is AOP-based — it uses Around Advice via
TransactionInterceptorto wrap your method with begin/commit/rollback logic.
- No magic — all the transaction management code exists in Spring's source code (
TransactionInterceptor,TransactionAspectSupport). It is just hidden from the developer.
- Class-level applies to all public methods — private methods are not intercepted by the AOP proxy.
- Default rollback behavior — only
RuntimeExceptionandErrortrigger rollback. Checked exceptions do NOT unless you configurerollbackFor.
- @EnableTransactionManagement is optional in Spring Boot — auto-configuration handles it. But if transaction management doesn't work, check if this annotation is missing.
- The annotation eliminates code duplication — the boilerplate exists once in Spring Framework, not in your application code.
- Works with any Spring-managed bean —
@Service,@Component,@Repository, etc.
Common Mistakes
Mistake 1 Forgetting `@EnableTransactionManagement` (in non-Boot projects)
1// ❌ Missing @EnableTransactionManagement in pure Spring (non-Boot) apps2@Configuration3public class AppConfig { }4
5// ✅ Correct6@Configuration7@EnableTransactionManagement8public class AppConfig { }Why it happens: Developers assume Spring auto-configures everything. In pure Spring (without Spring Boot), it does not. In Spring Boot, it is auto-configured.
Mistake 2 Using `@Transactional` on Private Methods
1// ❌ @Transactional on private method — has NO effect2@Transactional3private void updateUser() {4 // This transaction annotation is IGNORED5}6
7// ✅ Must be public8@Transactional9public void updateUser() {10 // This works correctly11}Why it happens: AOP proxies cannot intercept private methods. The proxy can only wrap public method calls.
Mistake 3 Self-Invocation Bypasses the Proxy
1@Service2public class UserService {3
4 public void processRequest() {5 // ❌ Calling @Transactional method from within the SAME class6 // This bypasses the AOP proxy — @Transactional has NO effect!7 this.updateUser();8 }9
10 @Transactional11 public void updateUser() {12 // Transaction does NOT start here when called via this.updateUser()13 }14}Why it happens: The AOP proxy wraps the UserService bean. When code inside UserService calls this.updateUser(), it calls the actual object — not the proxy. The proxy is bypassed, and the transaction never starts.
Fix: Extract the method into a separate bean, or use ApplicationContext to get a reference to the proxy.
Mistake 4 Expecting Rollback on Checked Exceptions
1// ❌ Checked exception does NOT trigger rollback by default2@Transactional3public void updateUser() throws IOException {4 userRepository.save(user);5 throw new IOException("File not found"); // Transaction COMMITS despite this!6}7
8// ✅ Must explicitly configure rollback for checked exceptions9@Transactional(rollbackFor = IOException.class)10public void updateUser() throws IOException {11 userRepository.save(user);12 throw new IOException("File not found"); // Now properly ROLLBACK13}Best Practices
- Apply
@Transactionalat the service layer, not the repository or controller layer. The service layer is where business transactions belong.
- Keep transactions short — long-running transactions hold database locks, reducing throughput and potentially causing deadlocks.
- Use
@Transactional(readOnly = true)for read-only operations. This is a performance optimization hint that allows the database to skip dirty-checking.
1 @Transactional(readOnly = true)2 public User getUser(Long id) {3 return userRepository.findById(id).orElseThrow();4 }- Never swallow exceptions inside a
@Transactionalmethod — if you catch an exception and don't rethrow it, the transaction will commit even though an error occurred.
- Specify
rollbackForfor checked exceptions when your method can throw checked exceptions that should trigger a rollback.
- Be aware of self-invocation — do not call
@Transactionalmethods from within the same class usingthis.methodName().
- Use declarative transactions (
@Transactional) over programmatic transactions unless you have very specific, fine-grained control needs.
Interview Notes
@Transactional.Q1: What is a Critical Section?
Answer: A critical section is a code segment where shared resources are accessed and modified. When multiple threads or requests access a critical section simultaneously without proper synchronization, data inconsistency can occur.
Q2: What are ACID properties?
Answer:
- Atomicity — All operations in a transaction succeed or all are rolled back.
- Consistency — The database is in a valid state before and after the transaction.
- Isolation — Concurrent transactions do not interfere with each other.
- Durability — Committed data persists even after system failure.
Q3: How does `@Transactional` work internally in Spring Boot?
Answer: @Transactional uses AOP (Aspect-Oriented Programming). When the application starts, Spring's AOP framework scans for @Transactional methods using a Pointcut expression. A proxy is created around annotated beans. When a @Transactional method is called, the proxy delegates to TransactionInterceptor.invokeWithinTransaction(), which begins a transaction, invokes the actual method, and commits on success or rolls back on exception.
Q4: What is the difference between class-level and method-level `@Transactional`?
Answer:
- Class-level: Applies to all public methods in the class. Private methods are not affected.
- Method-level: Applies only to the specific annotated method.
Q5: Does `@Transactional` roll back on checked exceptions?
Answer: No, by default it does not. @Transactional only rolls back on RuntimeException (unchecked) and Error. For checked exceptions, you must explicitly configure rollbackFor = Exception.class or rollbackFor = YourCheckedException.class.
Q6: Why doesn't `@Transactional` work when called from within the same class?
Answer: This is the self-invocation problem. Spring AOP uses proxies. When a method calls another method in the same class using this, it bypasses the proxy and calls the actual object directly, so the @Transactional AOP advice never executes.
Q7: What is `@EnableTransactionManagement`?
Answer: It enables Spring's annotation-driven transaction management capability. In Spring Boot, this is auto-configured and not required. In pure Spring, it must be explicitly added.
Q8: What advice type does `@Transactional` use internally?
Answer: Around Advice. It wraps the entire method — beginning a transaction before, and committing or rolling back after.
Topics Coming Next
The following topics will be covered in subsequent parts of this series:
| Topic | Description |
|---|---|
| Transaction Context | What transaction context is and how it is maintained |
| Transaction Manager Types | Different implementations (JpaTransactionManager, DataSourceTransactionManager, etc.) |
| Programmatic vs Declarative Transactions | Using TransactionTemplate vs @Transactional |
| Propagation | How transactions behave when one @Transactional method calls another |
| Isolation Levels | READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE |
| Transaction Timeout | Configuring how long a transaction can run |
| Read-Only Transactions | Performance optimization for read operations |
Summary
| Concept | Key Point |
|---|---|
| Critical Section | Code that accesses/modifies shared resources — vulnerable to race conditions |
| Data Inconsistency | Happens when multiple requests access a critical section without proper handling |
| ACID | Atomicity, Consistency, Isolation, Durability — properties guaranteed by transactions |
| @Transactional | Spring annotation that automatically manages begin/commit/rollback |
| Dependency | spring-boot-starter-data-jpa + database driver |
| @EnableTransactionManagement | Optional in Spring Boot; auto-configured |
| Class-level | Applies to all public methods |
| Method-level | Applies to specific method only |
| AOP | @Transactional uses Around Advice via TransactionInterceptor |
| Pointcut | Matches all methods annotated with @Transactional |
| Advice | TransactionInterceptor.invokeWithinTransaction() |
| Rollback | Default: RuntimeException and Error only |
| Self-invocation | Bypasses proxy — @Transactional has no effect |
@Transactional tells Spring: "Wrap this method in a transaction — begin before it runs, commit if it succeeds, rollback if it throws a RuntimeException." Everything else is taken care of by Spring's AOP infrastructure.End of Study Guide — Part 1 of @Transactional Series
Mastery check
How well can you recall this?
Finished this lesson?