TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท java ยท spring ยท databases ยท transactions

Spring transactions (@Transactional)

How Spring wraps a bean in a proxy that begins, commits or rolls back a database transaction around each @Transactional call, and how propagation, rollback rules, isolation, read-only hints and after-commit listeners shape that behaviour.

16 min6 animations

๐Ÿ“š Builds on๐ŸŒฑ Spring and Spring Boot๐Ÿ›’ Transactions and isolation

๐Ÿ–จ๏ธ Cheat sheet

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:

  1. Ask the PlatformTransactionManager (DataSourceTransactionManager for JDBC, JpaTransactionManager for JPA) to begin a transaction, and bind its connection to the current thread.
  2. Call the real method. Repositories, JdbcClient and the JPA EntityManager pick up that thread-bound connection.
  3. If the method returns, commit. If it throws an exception that matches the rollback rules, roll back, then rethrow.
1@Service2public class OrderService {3    private final OrderRepository orders;4    private final StockRepository stock;5 6    public OrderService(OrderRepository orders, StockRepository stock) {7        this.orders = orders;8        this.stock = stock;9    }10 11    @Transactional12    public void placeOrder(Order order) {13        orders.save(order);14        stock.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.

@Transactional works through a proxy6 steps
Records room0123๐Ÿง‘Customer๐Ÿง‘โ€๐Ÿ’ผClerk at the door๐Ÿง‘โ€โš–๏ธNotary
Press play and watch it happen!

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 {3    private final RowRepository repository;4 5    public ImportService(RowRepository repository) {6        this.repository = repository;7    }8 9    public void importAll(List<Row> rows) {   // not transactional10        saveBatch(rows);                      // this.saveBatch(): no proxy, no transaction11    }12 13    @Transactional14    public void saveBatch(List<Row> rows) {15        rows.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, protected and package-private methods are transactional with class-based proxies. Earlier versions honoured only public methods.
  • With interface-based (JDK) proxies, the method must be public and declared on the interface.
  • private methods are never intercepted, so the annotation on them is silently ignored. With CGLIB, a final method isn't intercepted either (it runs on the proxy instance, whose fields are unset), and a final class 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.

Self-invocation skips the proxy5 steps
Records room0123๐Ÿง‘Customer๐Ÿง‘โ€๐Ÿ’ผClerk at the door๐Ÿง‘โ€โš–๏ธNotary
Press play and watch it happen!

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 { ... }3 4@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().

Which exceptions roll back4 steps
Records room0123๐Ÿง‘โ€๐Ÿ’ผClerk at the door๐Ÿง‘โ€โš–๏ธNotary
Press play and watch it happen!

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.

PropagationTransaction already activeNo transaction active
REQUIRED (default)Joins itStarts one
REQUIRES_NEWSuspends it and starts an independent oneStarts one
NESTEDSets a savepoint inside it; a failure rolls back to the savepointStarts one
MANDATORYJoins itThrows IllegalTransactionStateException
SUPPORTSJoins itRuns without a transaction
NOT_SUPPORTEDSuspends it and runs without oneRuns without a transaction
NEVERThrowsRuns without a transaction
1@Service2class AuditService {3    private final AuditRepository audit;4 5    AuditService(AuditRepository audit) {6        this.audit = audit;7    }8 9    @Transactional(propagation = Propagation.REQUIRES_NEW)10    public void record(String event) {11        audit.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.

๐Ÿ”ง Going deeper

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.

REQUIRED joins, REQUIRES_NEW starts its own6 steps
๐Ÿง‘โ€โš–๏ธLead notary๐Ÿ’ฐPayments notary๐Ÿ“’Logbook notary๐Ÿ“ Folder A
Press play and watch it happen!

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:

  • isolation sets the isolation level, such as Isolation.READ_COMMITTED or Isolation.SERIALIZABLE. The default, Isolation.DEFAULT, uses the database's own default (READ COMMITTED on PostgreSQL, REPEATABLE READ on 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 = true is a hint. Spring passes it to the JDBC connection, and with Hibernate it sets the flush mode to MANUAL, 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.

Lazy loading after the transaction ends6 steps
๐Ÿง‘Customer๐Ÿง‘โ€๐Ÿ’ผClerk at the door๐Ÿง‘โ€โš–๏ธNotary๐Ÿ—„๏ธ Records room
Press play and watch it happen!

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 {3    private final TransactionTemplate tx;4    private final RowRepository repository;5 6    ImportService(PlatformTransactionManager manager, RowRepository repository) {7        this.repository = repository;8        this.tx = new TransactionTemplate(manager);9        this.tx.setTimeout(30);10    }11 12    void importAll(List<List<Row>> batches) {13        for (List<Row> batch : batches) {14            tx.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) {3    orders.save(order);4    events.publishEvent(new OrderPlaced(order.id())); // held until the transaction completes5}6 7@TransactionalEventListener // phase = AFTER_COMMIT8void sendConfirmation(OrderPlaced event) {9    mailer.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.

Work that waits for the commit5 steps
๐Ÿง‘โ€โš–๏ธNotary๐Ÿ“ Contract folder๐ŸƒMessenger๐Ÿ“ฎPost box
Press play and watch it happen!

๐Ÿ”Ž Spot it in real code

This is the notary's office as real Java code. The checkout notary writes the pages, and a second notary keeps the logbook. Pick a label, then tap the line where that happens. Can you find all five?

Tap the line where you see: The clerk's folder around the whole job.

0 of 5 placed

๐Ÿงฉ Finish the code

Now set up the notary's office yourself. If the card is declined, the order pages must be shredded, but the logbook entry must stay. The receipt letter may only go out once the folder is sealed, and never if it is shredded. Pick the code for each numbered gap.
  1. 1 Shred the folder when the card is declined, even though it is a complaint
  2. 2 Post the receipt letter only once the folder is sealed
  3. 3 The logbook always uses its own folder, sealed right away
1@Service2@RequiredArgsConstructor3public class OrderService {4    private final OrderRepository orders;5    private final PaymentClient payments;6    private final ApplicationEventPublisher events;7    private final AuditService audit;8    private final Mailer mailer;9 10    @Transactional(1)11    public void place(Order order) throws PaymentException {12        audit.record("place " + order.id());13        orders.save(order);14        events.publishEvent(new OrderPlaced(order.id()));15        payments.charge(order);16    }17 18    219    void sendReceipt(OrderPlaced event) { mailer.send(event.orderId()); }20}21 22@Service23@RequiredArgsConstructor24class AuditService {25    private final AuditRepository entries;26 27    @Transactional(3)28    void record(String event) { entries.save(new AuditEntry(event)); }29}
0 of 3 gaps filled

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Spring transactions (@Transactional), told the same way as the story.
  1. Halfway through a job, the notary does a part marked "needs a folder" right there at the same desk. What does the clerk do?
  2. The notary stops with a complaint they warned about in advance, and the clerk has no extra note. What happens to the folder?
  3. The logbook notary always uses their own folder. Later the lead notary's folder A is shredded. What happens to the logbook entry?
  4. The office doesn't keep folders open until the customer leaves. The customer gets the papers after their folder is sealed, then asks for the items the papers only point to. What happens?
  5. The notary hands the messenger a letter for the buyer, then the folder is shredded. What does the messenger do?
Answer every question to check.Passing marks Spring transactions (@Transactional) as done.
Got the hang of Spring transactions (@Transactional)? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ—ƒ๏ธ Spring and databasesStep 4 of 7

โ† Previous on the path๐Ÿ“‘ Database indexesNext on the path โ†’๐Ÿš• Connection pooling

๐Ÿ‘‰ Read next

  • ๐Ÿฝ๏ธThe N+1 query problem (JPA and Hibernate)A waiter who walks back to the kitchen once per diner for each side dish, instead of carrying one tray.