The clerk at the door
Picture a notary's office. Every job, like recording a house sale, gets its own contract folder. Each page the notary writes goes into that folder, and none of it counts until the folder is sealed and filed in the records room.
The notary doesn't handle folders at all. A clerk stands at the office door. When a customer brings a job, the clerk opens a fresh folder first, then lets the notary work. If the notary finishes, the clerk seals the folder and files it, so every page counts at once. If something goes wrong halfway, the clerk shreds the folder, so it's as if none of it happened.
The customer only ever talks to the clerk, and the notary only ever writes pages. In Spring, that clerk at the door is called a proxy.
Declarative transactions through a proxy
A transaction groups database changes so they commit together or not at all. In
Spring you rarely write BEGIN and COMMIT yourself; you mark a method with @Transactional
and Spring does it for you. This is declarative transaction management.
When a bean has @Transactional methods, the container injects a proxy in its place. Spring Boot creates
class-based (CGLIB) proxies by default; a JDK dynamic proxy that implements the bean's interfaces is the other kind.
The proxy's TransactionInterceptor runs around each call:
- Ask the
PlatformTransactionManager(DataSourceTransactionManagerfor JDBC,JpaTransactionManagerfor JPA) to begin a transaction, and bind its connection to the current thread. - Call the real method. Repositories,
JdbcClientand the JPAEntityManagerpick up that thread-bound connection. - If the method returns, commit. If it throws an exception that matches the rollback rules, roll back, then rethrow.
1@Service2public class OrderService {3private final OrderRepository orders;4private final StockRepository stock;56public OrderService(OrderRepository orders, StockRepository stock) {7this.orders = orders;8this.stock = stock;9}1011@Transactional12public void placeOrder(Order order) {13orders.save(order);14stock.decrement(order.items()); // throws a RuntimeException? the saved order is rolled back too15}16}
Because the transaction is bound to the thread, work handed to another thread (@Async, a CompletableFuture, a
parallel stream) does not take part in it.
Walking past the clerk
The clerk only sees jobs that come in through the door. Suppose a customer brings a big job that doesn't need a folder, and halfway through, the notary decides part of it does. If the notary just does that part at the same desk, nobody walks through the door, so the clerk never notices and never opens a folder. The pages go straight to the records room, one by one, and if the notary trips halfway, the first pages are already filed.
This trap of a notary calling on themself is called self-invocation. The fix is to pass that part to a second notary in another room, who has a clerk at their own door.
Self-invocation and method visibility
Only calls that arrive through the proxy are intercepted. A call from one method of a bean to another method on
this goes straight to the target object, so its @Transactional settings are ignored:
1@Service2public class ImportService {3private final RowRepository repository;45public ImportService(RowRepository repository) {6this.repository = repository;7}89public void importAll(List<Row> rows) { // not transactional10saveBatch(rows); // this.saveBatch(): no proxy, no transaction11}1213@Transactional14public void saveBatch(List<Row> rows) {15rows.forEach(repository::save); // each save commits on its own16}17}
Fixes, in order of preference: move saveBatch into another bean and inject it; annotate the outer method instead;
use a TransactionTemplate for the inner block; or switch to AspectJ weaving (mode = AdviceMode.ASPECTJ), which
changes the bytecode instead of using a proxy.
Visibility matters too, because a proxy can only intercept methods it can override or implement:
- Since Spring Framework 6.0,
protectedand package-private methods are transactional with class-based proxies. Earlier versions honoured onlypublicmethods. - With interface-based (JDK) proxies, the method must be
publicand declared on the interface. privatemethods are never intercepted, so the annotation on them is silently ignored. With CGLIB, afinalmethod isn't intercepted either (it runs on the proxy instance, whose fields are unset), and afinalclass can't be proxied at all, so startup fails.
@Transactional on the class applies to every method the proxy can intercept; an annotation on a method overrides
the class-level one.
Which trouble shreds the folder
Not all trouble is the same. A spill is an accident nobody planned for, like ink over the deed. A complaint is trouble the notary warned about in advance, like "the buyer hasn't signed yet". By default the clerk shreds the folder only for spills. For a complaint, the clerk assumes the notary has it under control, seals the folder anyway and passes the complaint on.
That surprises people, so you can leave the clerk a note: "shred for complaints too". These notes are the rollback rules.
Rollback rules
By default Spring rolls back on unchecked exceptions: RuntimeException and its subclasses, and Error. A
checked exception (Exception but not RuntimeException, such as IOException) is rethrown to the caller
after the transaction commits, so any work done before it stays.
Change that per method or per class:
1@Transactional(rollbackFor = Exception.class) // roll back on checked exceptions too2public void importFile(Path file) throws IOException { ... }34@Transactional(noRollbackFor = InsufficientStockWarning.class)5public void reserve(Item item) { ... }
rollbackForClassName and noRollbackForClassName take name patterns, matched as substrings, so use fully qualified
names. When several rules match, the most
specific one (closest in the exception's class hierarchy) wins.
The proxy only sees exceptions that leave the method. If you catch an exception inside the method and carry on, the
transaction commits. To roll back without throwing, call
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly().
Share the folder or start your own
Big jobs need several notaries. The lead notary opens folder A for a house sale and asks the payments notary to record the money. That clerk sees folder A already open and hands it straight in, so the payment pages land in the same folder: if the sale fails, the payment goes too.
The logbook notary, who writes down who came in and when, works differently. Their note says "always use your own folder". So the clerk puts folder A aside, opens folder B, and seals it as soon as the entry is written. Even if folder A is shredded later, the logbook entry stays.
How a job treats a folder that's already open is called propagation.
Propagation
propagation decides what happens when a @Transactional method is called while a transaction may already be
active. It only applies to calls through a proxy.
| Propagation | Transaction already active | No transaction active |
|---|---|---|
REQUIRED (default) | Joins it | Starts one |
REQUIRES_NEW | Suspends it and starts an independent one | Starts one |
NESTED | Sets a savepoint inside it; a failure rolls back to the savepoint | Starts one |
MANDATORY | Joins it | Throws IllegalTransactionStateException |
SUPPORTS | Joins it | Runs without a transaction |
NOT_SUPPORTED | Suspends it and runs without one | Runs without a transaction |
NEVER | Throws | Runs without a transaction |
1@Service2class AuditService {3private final AuditRepository audit;45AuditService(AuditRepository audit) {6this.audit = audit;7}89@Transactional(propagation = Propagation.REQUIRES_NEW)10public void record(String event) {11audit.save(new AuditEntry(event)); // committed even if the caller rolls back12}13}
REQUIRES_NEW is the usual choice for audit logs and for work that must survive the caller's rollback. It takes a
second connection while the first one is held, so with a small pool, many concurrent callers can exhaust it and
deadlock. Size the pool above the number of concurrent threads, by at least one (see
connection pooling). NESTED maps onto JDBC savepoints, so it only works with transaction managers that support them, such as
DataSourceTransactionManager.
The rollback-only trap: with REQUIRED, inner and outer methods share one physical transaction. If the inner
method throws a rollback exception, Spring marks the shared transaction rollback-only. If the outer method catches
that exception and returns normally, the commit can't happen: Spring rolls back and throws
UnexpectedRollbackException. Either let the exception propagate, or give the inner work its own transaction
(REQUIRES_NEW or NESTED) if failing it is genuinely acceptable.
The fine print on the folder
You can write more instructions on a folder's cover. "How much to see of other jobs" is a note that decides how much this notary may see of other notaries' work while it's still in progress. "Just looking" tells the clerk nothing will be changed, so there's no need to check every page for edits at the end.
There's one more catch. To keep folders light, a page often says "the list of items is in the records room" instead of copying it in. The records room only hands things over while the folder is open. So if the customer is given the papers after the folder is sealed and asks "what were the items?", nobody can fetch them. Fetching things only when someone asks is called lazy loading. The fix: fetch everything the customer will need while the folder is still open. Some offices keep the folder open until the customer has left, which hides the problem, but many switch that off.
Isolation, read-only and lazy loading
Other attributes tune the transaction itself:
isolationsets the isolation level, such asIsolation.READ_COMMITTEDorIsolation.SERIALIZABLE. The default,Isolation.DEFAULT, uses the database's own default (READ COMMITTEDon PostgreSQL,REPEATABLE READon MySQL InnoDB). See transactions for what each level allows.timeout(seconds) sets a deadline: database statements that run past it, or start after it, fail and the transaction rolls back.readOnly = trueis a hint. Spring passes it to the JDBC connection, and with Hibernate it sets the flush mode toMANUAL, which skips dirty checking. It does not reliably block writes: some databases reject them, while with Hibernate an entity change is silently never flushed.
isolation, timeout and readOnly apply only when a new transaction starts. A method that joins an existing transaction
runs with the outer one's settings.
Lazy loading depends on the transaction too. With JPA, the persistence context (the EntityManager) normally
lives as long as the transaction. A LAZY association, such as order.getItems(), is a placeholder that loads on
first access, which needs that persistence context open. Touch it after the @Transactional method has returned and
Hibernate throws LazyInitializationException (unless open-in-view is on, below). Loading lazy associations one by
one in a loop is also how the N+1 query problem starts.
Fix it by loading what the caller needs inside the transaction: a JOIN FETCH query, an @EntityGraph, or a DTO built
before returning. Spring Boot enables spring.jpa.open-in-view by default and logs a warning about it at startup: it
keeps the persistence context open for the whole web request, which hides the exception but runs queries while the
response is rendered. Many teams set it to false.
Doing it by hand, and waiting for the seal
Sometimes the notary wants a folder for just a few lines of a long job. Instead of sending that part through the door, the notary calls the clerk over: "a folder for these lines only, please". The clerk opens it, the notary writes, the clerk seals or shreds.
And some things must wait until the folder is sealed. Telling the buyer "your house is yours" before the seal would be a lie if the folder gets shredded. So the notary hands a letter to a messenger, who waits by the records room and only posts it once the folder is filed. If the folder is shredded, the letter is thrown away.
TransactionTemplate and after-commit work
For programmatic control, use TransactionTemplate. It runs a callback in a transaction: commit on return, roll back
if the callback throws or calls status.setRollbackOnly(). It is not
affected by self-invocation, because no proxy is involved.
1@Service2class ImportService {3private final TransactionTemplate tx;4private final RowRepository repository;56ImportService(PlatformTransactionManager manager, RowRepository repository) {7this.repository = repository;8this.tx = new TransactionTemplate(manager);9this.tx.setTimeout(30);10}1112void importAll(List<List<Row>> batches) {13for (List<Row> batch : batches) {14tx.executeWithoutResult(status -> batch.forEach(repository::save)); // one transaction per batch15}16}17}
Side effects outside the database, like emails or messages, should happen only after the commit. Publish an event
inside the transaction and handle it with @TransactionalEventListener, whose default phase is AFTER_COMMIT:
1@Transactional2public void placeOrder(Order order) {3orders.save(order);4events.publishEvent(new OrderPlaced(order.id())); // held until the transaction completes5}67@TransactionalEventListener // phase = AFTER_COMMIT8void sendConfirmation(OrderPlaced event) {9mailer.sendConfirmation(event.orderId());10}
If the transaction rolls back, the listener never runs. Other phases are BEFORE_COMMIT, AFTER_ROLLBACK and
AFTER_COMPLETION. If the event is published with no transaction active, the listener is skipped unless you set
fallbackExecution = true. After commit, the original transaction is finished: database writes in the listener won't
be committed unless they run in a new transaction (REQUIRES_NEW). And the commit is not atomic with the side effect,
so a crash between them loses the email; when that matters, write an outbox row in the same transaction instead.