🎯 What you will learn
A database transaction is an all-or-nothing unit of work. Spring's @Transactional wraps a service method in a single ACID transaction, automatically rolling back on unchecked exceptions. By the end of this lesson you will understand:
- ACID: Atomicity, Consistency, Isolation, Durability
- @Transactional on service methods — commit on success, rollback on RuntimeException
- rollbackFor and noRollbackFor — controlling rollback for checked exceptions
- Propagation.REQUIRED (default) vs Propagation.REQUIRES_NEW (independent transaction)
- readOnly = true — skips dirty-checking for pure read methods
- Isolation levels: READ_COMMITTED (default), REPEATABLE_READ, SERIALIZABLE
- Why @Transactional on private methods or via self-invocation has no effect
🏦 Real-world scenario
A fund transfer deducts ₹5,000 from Arjun's account and credits ₹5,000 to Vikram's. Without a transaction, a server crash between the two saves would lose money. @Transactional wraps both operations in one ACID unit — either both persist or neither does.
🔄 @Transactional on service method
Place @Transactional on the service layer — not the controller. The service knows the business logic that determines what counts as a single unit of work. Spring's AOP proxy intercepts the call, begins a transaction, and commits (or rolls back) when the method returns.
ACID in one line: Atomicity — all operations succeed or none do. Consistency — account balances never go negative. Isolation — concurrent transfers don't see each other's partial state. Durability — once committed, the transfer survives a crash.
⚖️ Balances before/after transfer — atomicity in action
The transfer subtracts ₹5,000 from Arjun and adds it to Vikram. Both accountRepo.save() calls happen inside the same transaction. If the second save threw an exception, Hibernate would roll back the first save too — leaving both balances unchanged.
🔀 Propagation and isolation levels
Propagation controls what happens when a @Transactional method is called from another. Isolation controls how concurrent transactions see each other's data. These are advanced but critical in financial systems.
When to use REQUIRES_NEW: Audit logging. You want the audit record of a failed transfer to persist even though the transfer itself rolled back. REQUIRES_NEW commits its own transaction before the outer transaction rolls back.
📋 Propagation levels — quick reference
| Propagation | Behaviour | Use case |
|---|---|---|
| REQUIRED (default) | Join existing TX; create new if none | Standard service methods |
| REQUIRES_NEW | Suspend outer TX; start fresh TX | Audit logs, notifications |
| SUPPORTS | Join if exists; no TX if none | Read methods that may or may not be in a TX |
| NOT_SUPPORTED | Suspend TX; run without TX | Batch reporting that must not lock |
| MANDATORY | Require an existing TX; throw if none | Internal helpers that must be called within a TX |
| NEVER | Throw if a TX exists | Methods that must never run in a TX |
📝 Quiz — 5 questions
Next: JUnit Basics →
🎤 Interview Q&A
Atomicity: all operations in a transaction succeed or all fail. Consistency: the database moves from one valid state to another. Isolation: concurrent transactions don't see each other's partial changes. Durability: committed data survives crashes.
Always on the service layer, not the controller. The service has the business logic that determines what constitutes a logical unit of work. Controllers should not know about transaction boundaries.
Spring implements @Transactional via AOP proxy. The proxy intercepts external calls and wraps them. When a method calls another method in the same class, it bypasses the proxy (self-invocation), so the inner method runs without its own transaction boundary. Fix: extract the inner method to a separate @Service.
Add @Version Long version to the entity. Hibernate includes version in UPDATE WHERE version = ? and increments it. If two transactions try to update the same row, the second throws OptimisticLockException. Catch it and retry or show the user a conflict error.
Spring creates a proxy (JDK dynamic proxy or CGLIB subclass) around the @Service bean. On method entry the proxy calls PlatformTransactionManager.getTransaction() to begin or join a transaction. On normal return it calls commit(). On RuntimeException it calls rollback(). The actual transaction is managed by a DataSourceTransactionManager (JDBC) or JpaTransactionManager, which binds the database connection/EntityManager to the current thread via ThreadLocal so all operations within the method use the same connection.
⚠️ Common mistakes
rollbackFor = Exception.class or use unchecked exceptions for rollback-worthy failures.@Service.✅ Key takeaways
- @Transactional on a service method = one ACID database transaction
- Automatic rollback on RuntimeException; add rollbackFor for checked exceptions
- Propagation.REQUIRES_NEW creates an independent transaction (audit logs)
- readOnly = true skips dirty-checking — use on all pure read service methods
- @Transactional on private methods or via self-invocation has NO effect
From @Transactional to production-ready Spring Boot
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →