🎯 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
💼 Interview reality: "When does @Transactional not work?" and "What is the difference between REQUIRED and REQUIRES_NEW?" appear in every senior Java backend interview. Self-invocation and checked exception rollback are the two most common gotchas.

🏦 Real-world scenario

🏦
SouthBank India (Mumbai)
Atomic debit + credit — both commit or both rollback

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.

curl -s -X POST "http://localhost:8766/api/accounts/transfer?from=SB-100001&to=SB-100003&amount=5000"
AccountService.javaLesson 30 · @Transactional transfer — atomic debit + credit
verified output — successful transfer{ "status": "SUCCESS", "message": "Transferred ₹5000.00 from SB-100001 to SB-100003" }

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.

curl -s http://localhost:8766/api/accounts
Rollback rules (comment block)Lesson 30 · RuntimeException vs checked Exception
verified output — balances after ₹5,000 transfer from SB-100001 to SB-100003[ { "id": 1, "accountNo": "SB-100001", "holderName": "Arjun Sharma", "balance": 80000.0, "accountType": "SAVINGS", "branch": {"id": 1, "code": "MUM01", "city": "Mumbai", "region": "Maharashtra"}, "createdAt": "2026-04-26T21:01:16.582733" }, { "id": 2, "accountNo": "SB-100002", "holderName": "Priya Mehta", "balance": 210000.0, "accountType": "CURRENT", "branch": {"id": 1, "code": "MUM01", "city": "Mumbai", "region": "Maharashtra"}, "createdAt": "2026-04-26T21:01:16.582733" }, { "id": 3, "accountNo": "SB-100003", "holderName": "Vikram Singh", "balance": 52500.0, "accountType": "SAVINGS", "branch": {"id": 2, "code": "DEL01", "city": "Delhi", "region": "Delhi"}, "createdAt": "2026-04-26T21:01:16.582733" }, { "id": 4, "accountNo": "SB-100004", "holderName": "Deepa Nair", "balance": 125000.0, "accountType": "SAVINGS", "branch": {"id": 3, "code": "BLR01", "city": "Bangalore", "region": "Karnataka"}, "createdAt": "2026-04-26T21:01:16.582733" } ]

🔀 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.

curl -s "http://localhost:8766/api/accounts/SB-100001/ledger"
AuditService.javaLesson 30 · Propagation.REQUIRES_NEW, readOnly, isolation
verified output — ledger entries created by the transfer, within the same transaction[ { "id": 1, "account": {"id": 1, "accountNo": "SB-100001", "holderName": "Arjun Sharma", "balance": 80000.0, "accountType": "SAVINGS", "branch": {"id": 1, "code": "MUM01", "city": "Mumbai", "region": "Maharashtra"}, "createdAt": "2026-04-26T21:01:16.582733"}, "type": "CREDIT", "amount": 10000.0, "description": "Salary deposit", "createdAt": "2026-04-26T21:01:16.583242" }, { "id": 2, "account": {"id": 1, "accountNo": "SB-100001", "holderName": "Arjun Sharma", "balance": 80000.0, "accountType": "SAVINGS", "branch": {"id": 1, "code": "MUM01", "city": "Mumbai", "region": "Maharashtra"}, "createdAt": "2026-04-26T21:01:16.582733"}, "type": "DEBIT", "amount": 2500.0, "description": "ATM withdrawal", "createdAt": "2026-04-26T21:01:16.583242" } ]

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

PropagationBehaviourUse case
REQUIRED (default)Join existing TX; create new if noneStandard service methods
REQUIRES_NEWSuspend outer TX; start fresh TXAudit logs, notifications
SUPPORTSJoin if exists; no TX if noneRead methods that may or may not be in a TX
NOT_SUPPORTEDSuspend TX; run without TXBatch reporting that must not lock
MANDATORYRequire an existing TX; throw if noneInternal helpers that must be called within a TX
NEVERThrow if a TX existsMethods that must never run in a TX

📝 Quiz — 5 questions

Question 1 of 5
What does @Transactional guarantee?
Question 2 of 5
When does Spring automatically roll back a @Transactional method?
Question 3 of 5
What does Propagation.REQUIRES_NEW do?
Question 4 of 5
What does @Transactional(readOnly = true) enable?
Question 5 of 5
Which isolation level is the PostgreSQL default?
0
/ 5
Quiz complete!

Next: JUnit Basics →

🎤 Interview Q&A

EasyWhat are ACID properties?
+

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.

EasyWhere should @Transactional be placed — controller or service?
+

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.

MediumWhy doesn't @Transactional work when you call a @Transactional method from within the same class?
+

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.

MediumHow do you handle optimistic locking in JPA?
+

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.

HardHow does Spring's @Transactional work under the hood?
+

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

Expecting rollback on checked exceptions
@Transactional only rolls back on RuntimeException by default. A method that throws IOException commits! Add rollbackFor = Exception.class or use unchecked exceptions for rollback-worthy failures.
Annotating @Transactional on private methods
Spring's proxy can't intercept private method calls. Put @Transactional only on public methods.
Self-invocation bypasses the proxy
Calling a @Transactional method from within the same bean skips the proxy. The inner method runs without a transaction boundary. Extract it to a separate @Service.
Mixing @Transactional and try/catch without re-throw
Catching a RuntimeException inside a @Transactional method and not re-throwing it prevents Spring from rolling back, because the proxy never sees the exception.

✅ 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
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →