Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 66 ยท Data Access

Transactions with @Transactional

Understand @Transactional in Spring Boot: how proxies start transactions, rollback rules, propagation, isolation, readOnly and the self-invocation pitfall.

Transferring money means two steps: take 100 from one account, add 100 to another. If the program fails between them, the money has vanished. A transaction groups steps so that either all of them happen or none of them do. Databases provide transactions, and Spring lets you declare them with a single annotation: @Transactional.

That one annotation is wonderfully short and surprisingly subtle. It works through proxies, which explains its two best-known surprises: checked exceptions do not roll back by default, and calling a transactional method from another method in the same class does nothing at all. This lesson shows how the annotation really works, the rules you must know (rollback, propagation, isolation, readOnly), and the places it bites.

The earlier lessons showed JDBC and JPA repositories; transactions are what hold them together. For the framework-level companion, see Spring Events and Transactions.

Spring cannot run on this site, so @Transactional is read-only here. The runnable stand-ins build the same mechanism by hand: a dynamic proxy that begins, commits and rolls back real H2 transactions, and shows exactly why self-invocation fails.

What a transaction promises

A transaction gives you the ACID guarantees: it is atomic (all or nothing), consistent (constraints hold), isolated (concurrent transactions do not trample each other) and durable (committed data survives a crash). In plain JDBC you manage this yourself with setAutoCommit(false), commit() and rollback(). Spring does it for you around a method call.

Java
@Service
class TransferService {

    private final AccountRepository accounts;

    TransferService(AccountRepository accounts) {
        this.accounts = accounts;
    }

    @Transactional
    public void transfer(long fromId, long toId, int amount) {
        Account from = accounts.findById(fromId).orElseThrow();
        Account to = accounts.findById(toId).orElseThrow();
        from.withdraw(amount);       // may throw: nothing is saved
        to.deposit(amount);
    }                                // commit happens here
}

If the method returns normally, Spring commits. If it throws a runtime exception, Spring rolls back. With JPA, changes to managed entities are flushed to the database at commit, so you do not even need to call save.

What @Transactional really does

A proxy Spring wraps your bean in a stand-in.
Begin The proxy opens a transaction first.
Your method The real code runs inside it.
Commit or roll back Decided by how the method ends.
1 / 2

Proxies: how the annotation works

Spring cannot change your class. Instead, when the container creates a bean with a @Transactional method, it hands out a proxy object wrapped around it. Callers receive the proxy. When they call a method, the proxy checks for the annotation, starts a transaction, delegates to the real object, and finally commits or rolls back.

sequenceDiagram
    participant C as Controller
    participant P as Proxy
    participant S as TransferService
    participant D as Database
    C->>P: transfer(1, 2, 100)
    P->>D: BEGIN
    P->>S: transfer(1, 2, 100)
    S->>D: UPDATE / UPDATE
    S-->>P: returns normally
    P->>D: COMMIT
    P-->>C: done

The transaction lives in the proxy; your method only sees the work in the middle.

This one picture explains almost every transaction surprise. If something calls your method without going through the proxy, nothing starts. If your method swallows an exception, the proxy sees a normal return and commits.

The stand-in below builds this mechanism with java.lang.reflect.Proxy and real H2. It uses its own @Transactional annotation and applies the same default rollback rule as Spring: runtime exceptions and errors roll back, checked exceptions commit unless rollbackFor says otherwise.

Java A transaction proxy with real rollbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the balances after each step. Step 2 shows a real rollback: the debit was undone, so the balances equal those after step 1. In step 3 the method threw a checked exception, yet the log says COMMIT and the money stayed moved (350 and 250): the caller saw an error, but the database kept the work. Step 4 runs the same code with rollbackFor, so the transfer is undone and the balances stay at 350 and 250. In real code, set @Transactional(rollbackFor = Exception.class) if you want every exception to roll back, or make your business exceptions unchecked.

The rules you must know

Rollback

By default, RuntimeException and Error trigger a rollback; checked exceptions do not. Two more traps follow from the proxy picture:

  • Catching the exception inside the method hides it from the proxy, and the transaction commits. If you catch, either rethrow, or call TransactionAspectSupport.currentTransactionStatus().setRollbackOnly().
  • If an inner transactional method that joined the outer transaction throws, the whole transaction is marked rollback-only even if the outer method catches the exception. The outer commit then fails with UnexpectedRollbackException.

Propagation

Propagation answers: "what if a transaction is already running when this method is called?"

  • REQUIRED (default): join the existing transaction, or start one if none exists.
  • REQUIRES_NEW: suspend the current one and run in a separate transaction with its own commit. Use it for work that must survive an outer rollback, such as writing an audit record.
  • MANDATORY: join the existing one, and fail if there is none.
  • SUPPORTS, NOT_SUPPORTED, NEVER, NESTED: rarer. NESTED uses savepoints and works only with some transaction managers.

Isolation

Isolation controls what concurrent transactions can see of each other: READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE. The default, DEFAULT, means "whatever the database does": PostgreSQL defaults to READ_COMMITTED, MySQL's InnoDB to REPEATABLE_READ. Change it only for a specific, understood reason. A stronger level costs throughput and can produce serialization failures that you must retry.

readOnly and timeout

@Transactional(readOnly = true) tells Spring and the JPA provider that no writes are intended. Hibernate skips dirty checking, and many drivers and replicas can route the work to a read connection. It is a hint, not a lock: do not rely on it to forbid writes. timeout = 5 (seconds) makes a transaction fail instead of holding locks for ever.

Put @Transactional(readOnly = true) on query services, and an explicit @Transactional on the few write methods that need it.

Where to place it

  • Put @Transactional on service-layer methods that represent a business operation, so each call is one unit of work. Not on controllers and not on every repository call. Spring Data's built-in save and delete are already transactional on their own.
  • Annotate public methods of Spring beans. Other visibilities depend on the proxy type, so avoid them.
  • Keep transactions short. An open transaction holds a database connection (a scarce pooled resource) and often locks. Never call a slow external HTTP service, send an email or wait for a user inside one. Do the slow call before or after, or use an event that fires after commit (see Spring Events and Transactions).
  • For code that needs to start a transaction by hand, use TransactionTemplate instead of an annotation.

The self-invocation pitfall

Because the transaction lives in the proxy, only calls that arrive through the proxy are transactional. Inside your class, this is the real object, not the proxy:

Java
@Service
class OrderService {

    @Transactional
    public void placeOrder() {
        // ... save the order ...
        this.writeAudit("order placed");       // direct call: bypasses the proxy
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void writeAudit(String text) {
        // expected: separate transaction. actual: just part of placeOrder's
    }
}

The annotation on writeAudit is silently ignored in the call above. There is no error and no warning, only wrong behavior. The same applies to @Cacheable, @Async and @Retryable, which all work through proxies. The fixes, best first:

  1. Move the method into another bean and inject that bean. This is the cleanest design.
  2. Inject the bean into itself (with @Lazy) and call it through that reference.
  3. Use TransactionTemplate inside the method.

The second stand-in shows the pitfall in miniature: a proxy that supports REQUIRED and REQUIRES_NEW, and a service that calls audit first through this and then through the proxy.

Java Self-invocation bypasses the proxy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In the broken version there is no BEGIN for audit: it ran inside the outer transaction, so an exception in the outer method would erase the audit record too. In the fixed version the call arrives at the proxy, which suspends the outer transaction and starts a new one (tx#3) just for the audit.

Transactions and the web layer

Spring Boot enables open-in-view by default (spring.jpa.open-in-view=true): the JPA session stays open until the HTTP response is written, so lazy collections still load while a controller or view renders. That convenience hides missing fetches (as seen in Entity Relationships and the N+1 Problem), keeps a connection busy during rendering and runs queries outside any transaction. Boot logs a warning about it at startup. Switch it off, load what you need inside the service transaction, and return DTOs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does @Transactional on a method have no effect when another method of the same class calls it?

    The transaction is started by a proxy around the bean. A call from inside the class uses the real object directly, so the proxy never sees it.
  2. 2. What happens by default when a transactional method throws a checked exception?

    Spring rolls back on RuntimeException and Error only. Use rollbackFor (for example Exception.class) if checked exceptions should roll back too.
  3. 3. Which propagation setting runs a method in a new, separate transaction and suspends the current one?

    REQUIRES_NEW suspends the running transaction and commits independently, which suits audit records that must survive an outer rollback.
  4. 4. Where should @Transactional normally be placed in a layered application?

    A service method is the natural unit of work. Controllers should stay thin, and repositories already provide their own transactions for single operations.
  5. 5. Why is it a bad idea to call a slow external HTTP service inside a transaction?

    An open transaction occupies one of a few pooled connections and may hold database locks. Slow external calls make other requests wait.

Summary

  • @Transactional is applied by a proxy: it begins, then commits or rolls back around your method.
  • Runtime exceptions and errors roll back by default; checked exceptions commit unless you set rollbackFor. Catching an exception inside the method hides it from the proxy.
  • REQUIRED joins an existing transaction; REQUIRES_NEW runs separately. Isolation defaults to the database's default.
  • Use readOnly = true for queries, and keep transactions short, with no slow external calls inside.
  • Place @Transactional on public service methods that mark one unit of work.
  • Self-invocation bypasses the proxy; move the method to another bean (or call through an injected proxy) to fix it.
  • Switch off open-in-view and return DTOs instead of relying on lazy loading in controllers.

Next: Database Migrations with Flyway.