The Analogy: Settling the Day's Takings at a Bank Branch
At close of business a bank branch has to post the day's transactions to the master ledger. The head clerk does not write each deposit and withdrawal straight into the ledger as it happens. Every entry is first staged on a settlement sheet: cash counted, slips matched, totals pencilled in. Nothing touches the permanent ledger until the whole sheet balances and the clerk signs it off. The settlement sheet is a boundary drawn around a set of related entries that must all become permanent together, or not at all.
If a single entry is wrong -- a deposit slip whose figures do not match the cash in the drawer -- the clerk does not post the good entries and leave the bad one for tomorrow. The entire settlement sheet is torn up and the day is re-reconciled from scratch. The alternative, posting each entry to the master ledger the moment it is written, seems faster until the clerk is interrupted halfway through: now some money has moved and some has not, and there is no clean record of where the process stopped. All-or-nothing is slower per entry and far safer overall.
After settlement the branch must send the supporting documents to the regional office across town. A sensible clerk gathers every document for the day into one dispatch bag and hands it to the courier in a single trip. A careless clerk hands the courier one document, waits for the round trip across town and back, then hands over the next document, and repeats. Both clerks send the same paperwork. One does it in a single journey; the other makes one journey per document.
The careless dispatch looks perfectly fine on a quiet day with three documents -- three quick trips, nobody notices. On a busy day with a hundred documents it becomes a hundred round trips and the courier never gets home. Worse still, if the clerk waits until after the settlement sheet has been filed and locked in the vault before starting to fetch the documents it references, some of those papers are now sealed away and cannot be retrieved at all. The task fails not because any single trip is wrong, but because the number of trips grew with the workload and the timing left records out of reach.
Syntax or Core Structure
A transaction is a settlement sheet drawn around a group of writes. In Spring you draw that boundary with @Transactional on a service method, so every write inside it commits together or rolls back together.
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final InventoryService inventoryService;
private final PaymentService paymentService;
public OrderService(OrderRepository orderRepository,
InventoryService inventoryService,
PaymentService paymentService) {
this.orderRepository = orderRepository;
this.inventoryService = inventoryService;
this.paymentService = paymentService;
}
@Transactional
public OrderResponse place(CreateOrderRequest request) {
orderRepository.save(Order.from(request)); // 1 save order
inventoryService.reserve(request); // 2 reserve inventory
paymentService.charge(request); // 3 charge payment (may throw)
return OrderResponse.confirmed(request);
}
}
Trace what happens when the payment step throws a RuntimeException after the first two writes have already been staged. Inside one @Transactional method the failure rolls the whole unit back, so nothing persists. Without the annotation each write would commit on its own, leaving reserved stock with no payment.
Output:
operation status
----------------------------------------------
1 save order staged
2 reserve inventory staged
3 charge payment FAILS (RuntimeException)
----------------------------------------------
in one @Transactional : rolled back
rows persisted (tx) : 0
rows persisted (no tx) : 2
partial state possible : yes
The transaction turns three separate writes into one settlement sheet: the failed payment tears up the sheet and the two earlier writes vanish with it. Put the boundary on the repository instead of the service and you get the "no tx" column -- two committed rows and a broken invariant.
Technical Depth: What Triggers a Rollback and Why N+1 Hides
The default rollback rule surprises everyone once
Drawing the boundary is only half the contract. The other half is deciding what counts as "the sheet did not balance". Spring's default is that a transaction rolls back on an unchecked throwable -- anything extending RuntimeException or Error -- and commits on a checked exception. That last part is the trap: a method can throw a checked IOException, the caller sees an error, and yet the transaction has already committed.
// commits even though it throws -- IOException is checked
@Transactional
public void importFile() throws IOException {
repository.save(row);
reader.read(); // throws IOException; save() is NOT rolled back
}
// override the default so any exception rolls back
@Transactional(rollbackFor = Exception.class)
public void importFileSafely() throws IOException { ... }
The table below is the whole rule for the default @Transactional with no rollbackFor set.
| Throwable thrown | Extends | Default behaviour |
|---|---|---|
| RuntimeException | RuntimeException | rollback |
| IllegalArgumentException | RuntimeException | rollback |
| Error | Error | rollback |
| IOException | Exception (checked) | commit |
| Exception | Exception (checked) | commit |
Output:
throwable thrown default behaviour
--------------------------------------------------
RuntimeException rollback
IllegalArgumentException rollback
Error rollback
IOException commit (no rollback)
Exception commit (no rollback)
--------------------------------------------------
roll back : 3
commit despite throw : 2
fix for checked : rollbackFor = Exception
Three of the five roll back; the two checked exceptions commit despite throwing. If a method that writes can fail with a checked exception, either add rollbackFor = Exception.class or wrap the checked exception in a runtime one before it leaves the method.
N+1 is a query count, not a slow query
The courier making one trip per document is the N+1 problem exactly. You fetch a list of N rows in one query, then touch a lazy association on each row in a loop -- and each touch is its own query. No single query is slow; there are simply N+1 of them.
List<Order> orders = orderRepository.findAll(); // 1 query for the list
for (Order order : orders) {
order.getCustomer().getName(); // 1 query per order
}
The fix is to fetch the associations in the same trip. A join fetch collapses everything into one query; a default_batch_fetch_size of 50 turns 100 follow-up queries into a small fixed number instead of one-per-row.
@Query("select o from Order o join fetch o.customer")
List<Order> findAllWithCustomer(); // one query, customers populated
Output:
strategy queries vs naive
----------------------------------------------
naive lazy loop 101 baseline
join fetch 1 -100
batch fetch 50 3 -98
----------------------------------------------
orders : 100
naive queries : 101
join fetch queries : 1
batch fetch queries : 3
The naive loop over 100 orders issues 101 queries; the join fetch issues 1. Batch fetching does not eliminate the follow-up trips but bounds them: 100 rows at batch size 50 is 1 list query plus 2 batched loads, so 3 in total.
Real World Example: A Report Endpoint That Runs Without a Transaction
Here is a reporting service that looks correct and fails in a way that is genuinely hard to spot. The intent is that loadAll runs inside a read-only transaction so the lazy customer association stays reachable while the loop builds each row.
@Service
public class ReportService {
private final OrderRepository orderRepository;
public ReportService(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
// no @Transactional here
public Report report() {
return loadAll(); // self-invocation: calls this.loadAll()
}
@Transactional(readOnly = true)
public Report loadAll() {
List<Order> orders = orderRepository.findAll(); // 50 orders
List<Row> rows = new ArrayList<>();
for (Order order : orders) {
rows.add(new Row(order.getCustomer().getName())); // lazy, per row
}
return new Report(rows);
}
}
The @Transactional on loadAll is real and correctly written, but it never takes effect. @Transactional is applied by a proxy that wraps the bean: only calls that arrive through the proxy from outside are intercepted. When report() calls loadAll() it is really calling this.loadAll(), which goes straight to the target object and skips the proxy. No transaction starts, and the read-only optimisation and the open persistence context both never happen.
Output:
method @Transactional tx started
------------------------------------------------
report() no no
this.loadAll() yes no
------------------------------------------------
annotations present : 1
transactions started : 0
queries issued : 51
root cause : self-invocation bypass
The count that gives the bug away is the second-to-last line: one @Transactional annotation is present and yet zero transactions start. Because there is no open persistence context, the loop over 50 orders lazily loads each customer as its own query and the endpoint issues 51 queries -- and on a different mapping it would instead throw LazyInitializationException the moment the loop touches a customer, which is the documents being sealed in the vault before the clerk fetched them. There are two design flaws stacked here: the transaction boundary is defeated by self-invocation, and the read path is written as a lazy loop rather than a single fetch. The honest fix is to move loadAll to a separate injected bean (so the call crosses a proxy) and to fetch customer with a join, which fixes the boundary and the N+1 together.
Common Mistakes
- Putting
@Transactionalon the repository instead of the service. Each repository call becomes its own transaction, so a multi-write use case can commit some writes and fail others. Draw the boundary around the whole use case, in the service method that orchestrates it.
- Assuming a checked exception rolls back. By default only
RuntimeExceptionandErrorroll back; a checkedIOExceptioncommits despite throwing. AddrollbackFor = Exception.classor wrap the checked exception in a runtime one.
- Calling a
@Transactionalmethod from within the same bean. Self-invocation bypasses the proxy, so the annotation does nothing and no transaction starts. Move the method to a separate injected bean if it must run in its own transaction.
- Making
@Transactionalmethods non-public or final. The proxy can only intercept public, overridable methods; a private or final method is silently non-transactional. Keep transactional entry points public.
- Touching a lazy association outside the transaction. Once the persistence context closes, a lazy getter throws
LazyInitializationException. Map to your response DTO inside the transactional method, while the context is still open.
- Leaving
@ManyToOneon its default ofEAGER. Every query silently drags the related table along, even when a use case does not need it. Setfetch = FetchType.LAZYand fetch explicitly where required.
- Diagnosing N+1 as a slow query. No individual query is slow; there are simply N+1 of them. Count the queries in the SQL log rather than profiling one statement.
- Fixing N+1 with EAGER fetching. Making an association eager just moves the extra work into every query, including the ones that never touch the association. Use
join fetchor an entity graph on the specific query that needs it.
- Wrapping the whole service in one giant
@Transactional. Long transactions hold locks and database connections for their entire duration and starve the pool under load. Keep the boundary as tight as the invariant it protects.
Best Practices
- Put transaction boundaries on service methods that represent a complete unit of work, not on repositories or controllers.
- Add
rollbackFor = Exception.classto any transactional method that declares a checked exception, so a thrown error never commits partial state. - Mark read-only paths with
@Transactional(readOnly = true)so Hibernate skips dirty-checking and the driver can route to a replica. - Default associations to
FetchType.LAZYand fetch what a use case needs explicitly withjoin fetchor@EntityGraph. - Map entities to response DTOs inside the transactional method, while the persistence context is still open.
- Turn on
show-sqlandformat_sqlin development and watch the log while exercising an endpoint to catch N+1 before users do. - Set a
default_batch_fetch_sizeso any lazy loading that slips through is bounded instead of one-query-per-row. - Keep transactions short: acquire nothing you do not need inside the boundary, and never call a slow external service while a transaction holds a connection.
Practice Exercises
- A service annotated
@Transactionalsaves an order, then calls an inventory method that throws a checkedInsufficientStockException. The order is committed anyway even though stock was never reserved. Explain why the rollback did not happen and give two ways to fix it.
- An endpoint listing 50 invoices with their customer and their line items issues 151 queries. Identify the two associations at fault, explain the arithmetic that produces 151, and give two different fixes.
- A developer adds
@Transactionalto a private helper method and is puzzled that no transaction ever starts. Explain the proxy mechanism that causes this and describe the change that makes the boundary take effect.
- A report builder loads entities in a transactional method, returns them to the controller, and the controller throws
LazyInitializationExceptionwhile serialising a lazy field. Explain why the context was already closed and rewrite the flow so the association is loaded in time.