Lesson 12 of 12 · 11 min · Data access with Spring Data JPA
Transactions with @Transactional
What you will learn
- What
@Transactionaldoes and how it is implemented (proxies) - Where to place it and why in the service layer
- Rollback rules for runtime and checked exceptions
- Propagation (
REQUIRED,REQUIRES_NEW) and isolation in practice readOnly, self-invocation, and keeping transactions short
In simple words
A transaction is "all or nothing": if you move money between two accounts, either both steps happen or neither does. In plain JDBC you would write commit and rollback yourself. In Spring you put one word, @Transactional, on a method. Spring starts a transaction before the method, commits when it finishes normally and rolls back when it fails. The database lesson on ACID showed why this matters; this lesson shows how to use it correctly.
Words to know
- Transaction: a group of database operations that succeed or fail together.
- Proxy: a wrapper object Spring puts around your bean to add behaviour such as transactions.
- Rollback: undoing all changes made in a transaction.
- Propagation: what happens when a transactional method calls another transactional method.
The basics
@Service
public class TransferService {
private final AccountRepository accounts;
TransferService(AccountRepository accounts) { this.accounts = accounts; }
@Transactional
public void transfer(long fromId, long toId, BigDecimal amount) {
Account from = accounts.findById(fromId).orElseThrow();
Account to = accounts.findById(toId).orElseThrow();
from.withdraw(amount); // throws if the balance is too low
to.deposit(amount);
// no save() needed: managed entities are written when the transaction commits
}
}
- Before
transferruns, Spring opens a transaction and a JPA persistence context. - Inside it, entities loaded are managed: Hibernate tracks changes and issues the
UPDATEstatements at commit (dirty checking). - If the method returns normally, Spring commits. If it throws a
RuntimeException, Spring rolls back, and neither account changes.
Use org.springframework.transaction.annotation.Transactional (Spring's own, with more options) rather than jakarta.transaction.Transactional.
How it works: proxies
Spring does not change your class. It wraps the bean in a proxy that opens the transaction, calls your method, then commits or rolls back. Consequences you must remember:
@Transactionalworks only on calls that go through the proxy: calls from other beans.- It works on public methods (non-public methods are ignored by default proxying).
- Self-invocation does not work. If a method in the same class calls another
@Transactionalmethod withthis.other(), the call bypasses the proxy and the annotation onother()is ignored:
@Service
class ReportService {
public void process() {
saveAudit(); // direct call: NOT transactional, even though saveAudit has the annotation
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void saveAudit() { ... }
}
Fix by moving saveAudit to another bean and injecting it, or by structuring the code so the transactional method is the entry point.
finalclasses and methods cannot be proxied by the default mechanism (Boot uses CGLIB class proxies; Kotlin needs theallopenplugin).- A
@Transactionalprivate method is never transactional.
Where to put it
Put @Transactional on service methods, which define a unit of business work, not on repositories (Spring Data repository methods are already transactional; save and friends each run in their own if there is no outer one) and not on controllers (it would hold a transaction while serialising the response).
Class-level @Transactional applies to all public methods; override per method:
@Service
@Transactional(readOnly = true) // default for the whole class: reads
public class OrderQueryService {
public OrderResponse get(long id) { ... }
@Transactional // this one writes
public void markPaid(long id) { ... }
}
Rollback rules
By default Spring rolls back on unchecked exceptions (RuntimeException and Error), and commits on checked exceptions (IOException, Exception subclasses you declare). This surprises people:
@Transactional
public void placeOrder() throws PaymentException { // checked
orders.save(order);
paymentGateway.charge(order); // throws PaymentException: the order is STILL committed
}
Change the rule when needed:
@Transactional(rollbackFor = PaymentException.class)
@Transactional(noRollbackFor = DuplicateEmailException.class)
This is one more reason to prefer unchecked domain exceptions (previous Core Java lessons). Do not swallow the exception: catching it inside the method and carrying on means the proxy never sees it, so the transaction commits whatever was done so far. If you must catch, rethrow, or mark rollback explicitly with TransactionAspectSupport.currentTransactionStatus().setRollbackOnly().
If an exception is thrown in an inner transactional method joined to an outer one and you catch it in the outer method, the whole transaction may already be marked rollback-only, and the commit then fails with UnexpectedRollbackException.
Propagation
What happens when a transactional method calls another transactional method on a different bean?
| Propagation | Behaviour |
|---|---|
REQUIRED (default) |
join the existing transaction, or start one if none exists |
REQUIRES_NEW |
suspend the current one and start a new, independent transaction |
SUPPORTS |
join if one exists, otherwise run without |
MANDATORY |
must already be inside one, else throw |
NOT_SUPPORTED |
run without a transaction (suspends the current one) |
NEVER |
throw if a transaction exists |
NESTED |
a savepoint inside the current transaction (JDBC, not all providers) |
REQUIRED is right for almost everything: the whole business operation succeeds or fails together. Use REQUIRES_NEW for work that must survive a rollback of the outer transaction, such as an audit log or a failure record: it commits independently. Remember each REQUIRES_NEW takes another database connection, so many of them under load can exhaust the pool.
Isolation and timeouts
@Transactional(isolation = Isolation.REPEATABLE_READ) sets the isolation level for the transaction (see the ACID lesson); the default is the database's own (Read Committed in PostgreSQL). Change it only with a reason, such as consistent multi-query reports or strict booking rules. @Transactional(timeout = 10) limits how long (seconds) it may run.
Read-only transactions
@Transactional(readOnly = true)
public List<OrderResponse> recentOrders() { ... }
readOnly = true is a hint: Hibernate skips dirty checking and flushing (saving CPU and memory), and some databases route the work to a replica or reject writes. It is a good default for query-only service methods. It does not make writes impossible in every setup, so treat it as an optimisation and safety hint.
Keep transactions short
A transaction holds a database connection and often locks. From the SQL lesson on transactions:
- Do not call slow external services (an HTTP payment gateway, an email server) inside a transaction: the connection and locks stay held while you wait, and a timeout could leave a charged payment with a rolled-back order.
- Do not wait for user input or do heavy computation inside.
- Do the external call outside, or after commit, using
@TransactionalEventListener(phase = AFTER_COMMIT)(send the email only if the order really committed), or an outbox table written in the same transaction and processed by a separate job. - Catch optimistic locking failures (
ObjectOptimisticLockingFailureException) and retry or return 409.
@Transactional
public Order place(CreateOrderRequest r) {
Order order = orders.save(Order.from(r));
events.publishEvent(new OrderPlaced(order.getId())); // listener runs after commit
return order;
}
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
void onOrderPlaced(OrderPlaced event) { emailService.sendReceipt(event.orderId()); }
Testing transactions
@DataJpaTest and @Transactional tests roll back at the end of each test by default, which keeps tests independent but can hide commit-time behaviour (constraint checks, AFTER_COMMIT listeners, version checks that run at flush). For those, flush explicitly (entityManager.flush()), or use @Commit or a non-transactional test with cleanup. A test that asserts a rollback should call the service, catch the exception, and then check the data.
Common mistakes
- Self-invocation of a transactional method.
@Transactionalon private or non-public methods.- Expecting a rollback on checked exceptions.
- Catching the exception inside and swallowing it.
- Calling remote services inside a transaction.
- Putting
@Transactionalon controllers or on the whole application "to be safe". - Loading entities, leaving the transaction, and then touching lazy fields.
- Overusing
REQUIRES_NEW, draining the connection pool.
Try it yourself
- Write
transferand prove with a test that a failing deposit rolls back the withdrawal. - Make the exception checked and show that the transaction commits; then fix it with
rollbackFor. - Reproduce the self-invocation bug and fix it by moving the method to another bean.
- Add an audit record with
REQUIRES_NEWthat survives a rolled-back outer transaction. - Send a confirmation email with
@TransactionalEventListener(AFTER_COMMIT)and verify it is not sent when the order fails.
Check yourself
How does @Transactional work?
Spring wraps the bean in a proxy that opens a transaction before the method, commits after a normal return and rolls back on a runtime exception, so it only applies to calls that go through the proxy.
Which exceptions cause a rollback by default?
Unchecked exceptions (RuntimeException and Error); checked exceptions commit unless you set rollbackFor.
Why does a @Transactional method called from another method of the same class not start a transaction?
The call is a direct this call that bypasses the proxy, so the transaction advice never runs.
What does Propagation.REQUIRES_NEW do?
It suspends the current transaction and runs the method in a new, independent transaction that commits or rolls back separately.
Interview questions
Explain @Transactional, propagation and isolation in Spring.
@Transactional demarcates a transaction through a proxy. Propagation decides how nested calls join transactions (REQUIRED joins or creates, REQUIRES_NEW always starts a new one). Isolation sets the database isolation level; the default is the database's own.
Why does @Transactional not roll back on a checked exception, and how do you change it?
Spring follows EJB convention: checked exceptions are treated as business conditions and commit. Use @Transactional(rollbackFor = X.class) or throw unchecked exceptions.
How do you send an email only if a transaction commits?
Publish an application event inside the transaction and handle it with @TransactionalEventListener(phase = AFTER_COMMIT), or write to an outbox table in the same transaction and process it asynchronously.
Summary
@Transactionalon service methods gives all-or-nothing behaviour through a proxy; commit on success, rollback on runtime exceptions.- Self-invocation, private methods and swallowed exceptions defeat it; checked exceptions need
rollbackFor. REQUIREDis the default; useREQUIRES_NEWsparingly; usereadOnlyfor queries.- Keep transactions short; do external calls after commit or through an outbox.
Going deeper
- Spring Framework: Declarative transaction management:
@Transactionalin detail. - Using @Transactional: settings, proxies and self-invocation.
- Transaction propagation: required, requires new and nested.
- Transaction-bound events:
@TransactionalEventListener.
See how much of this you can explain
A free mock interview asks you new questions on Spring Boot, REST and JPA for Java Full Stack Developer and scores every answer, with what to fix.