Chapter 09

Transactions

@Transactional is one word that hides a proxy, a thread-local, a connection and a set of rollback rules. Almost every "my transaction did not roll back" bug is one of five things, all of them on this page.

⏱ 18 min readLevel: intermediateCore chapter

The mechanism

Spring does not modify your bytecode. It wraps your bean in a proxy that runs the transaction management around your method:

what the proxy effectively does
public void placeOrder(Order order) {

    TransactionStatus tx = transactionManager.getTransaction(definition);
    try {
        target.placeOrder(order);          // ← your actual method
        transactionManager.commit(tx);
    } catch (RuntimeException | Error e) {
        transactionManager.rollback(tx);   // unchecked → rollback
        throw e;
    } catch (Exception e) {
        transactionManager.commit(tx);     // checked → COMMIT by default!
        throw e;
    }
}

Three consequences follow directly, and they explain most of the confusion: the annotation only works when the call comes through the proxy; only public methods can be proxied; and checked exceptions do not roll back.

Where the boundary belongs

order/OrderService.java
@Service
public class OrderService {

    private final OrderRepository orders;
    private final StockService stock;
    private final PaymentGateway payments;

    // constructor omitted

    @Transactional                                   // ← the service, not the controller
    public Order place(PlaceOrderCommand command) {

        Order order = new Order(command.customerId());

        for (OrderLineCommand line : command.lines()) {
            stock.reserve(line.bookId(), line.quantity());   // joins THIS transaction
            order.addLine(line.bookId(), line.quantity(), line.unitPrice());
        }

        orders.save(order);
        return order;
    }

    @Transactional(readOnly = true)
    public Order require(Long id) {
        return orders.findById(id).orElseThrow(() -> new OrderNotFoundException(id));
    }
}
LayerTransactional?Why
ControllerNoThe boundary would then include JSON serialisation and HTTP concerns
ServiceYesThis is the unit of business work — the correct atomicity boundary
RepositoryInheritedSpring Data methods are already transactional; they join the caller's transaction

readOnly = true

Not just documentation. On a read path it:

  • Sets the Hibernate flush mode to MANUAL, skipping dirty-checking entirely.
  • Marks the JDBC connection read-only, which some drivers and proxies use to route to a replica.
  • Lets Hibernate skip taking snapshots of loaded entities — a real memory and CPU saving on large reads.
It does not prevent writes

With JPA a write inside a readOnly transaction usually fails, but through plain JDBC or MyBatis it may silently succeed depending on the driver. Treat it as an optimisation and an intent marker, not a security control.

Propagation

What happens when a transactional method calls another transactional method.

PropagationTransaction existsNo transactionUse for
REQUIRED (default)join itstart oneAlmost everything
REQUIRES_NEWsuspend it, start a new onestart oneAudit rows that must survive a rollback
SUPPORTSjoin itrun without oneRead methods callable either way
NOT_SUPPORTEDsuspend itrun without oneLong non-transactional work
MANDATORYjoin itthrowEnforcing that a caller opened one
NEVERthrowrun without oneRare
NESTEDsavepointstart onePartial rollback (JDBC only, not JPA)
the classic REQUIRES_NEW case
@Service
public class AuditService {

    /* The audit record must persist even if the caller rolls back. */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void record(String action, String detail) {
        auditRepository.save(new AuditEntry(action, detail, Instant.now()));
    }
}
REQUIRES_NEW borrows a second connection

The outer transaction is suspended but keeps holding its connection while the inner one takes another from the pool. Call it in a loop over 50 items with a pool of 20 and you deadlock the pool against itself. Use it deliberately, never in a loop.

Rollback rules

the default, and how to change it
// rolls back:   RuntimeException, Error
// does NOT roll back: checked Exception  ← surprises everyone once

@Transactional(rollbackFor = Exception.class)          // roll back on anything
public void importFile(Path path) throws IOException { }

@Transactional(noRollbackFor = InsufficientStockException.class)
public void reserve(Long bookId, int quantity) { }

The simplest defence: make your domain exceptions extend RuntimeException. Then the default rule is the rule you want, everywhere.

Catching an exception inside a transaction

the UnexpectedRollbackException trap
@Transactional
public void processAll(List<Order> orders) {
    for (Order order : orders) {
        try {
            processOne(order);          // another bean, @Transactional REQUIRED
        } catch (Exception e) {
            log.warn("Skipping order {}", order.getId(), e);   // looks harmless
        }
    }
    // commit → org.springframework.transaction.UnexpectedRollbackException:
    //          Transaction silently rolled back because it has been marked as rollback-only
}

The inner method joined the same physical transaction. Its exception marked the whole transaction rollback-only, and catching it did not clear that flag. Two correct fixes:

  1. Make processOne REQUIRES_NEW, so its failure is isolated.
  2. Move the loop outside the transaction and start one per item.

Self-invocation: the number one bug

this does nothing
@Service
public class ReportService {

    public void generateAll() {
        for (Long id : ids) {
            this.generateOne(id);        // ← plain Java call, proxy not involved
        }
    }

    @Transactional
    public void generateOne(Long id) {
        // NO transaction here when reached via generateAll()
    }
}
three ways to fix it
// 1 · BEST — move the transactional method to its own bean
@Service
public class ReportGenerator {
    @Transactional
    public void generateOne(Long id) { }
}

// 2 · inject yourself lazily (works, but signals a design smell)
@Service
public class ReportService {

    private final ReportService self;

    public ReportService(@Lazy ReportService self) {
        this.self = self;
    }

    public void generateAll() {
        ids.forEach(self::generateOne);   // through the proxy
    }
}

// 3 · programmatic — explicit and proxy-free
@Service
public class ReportService {

    private final TransactionTemplate tx;

    public void generateOne(Long id) {
        tx.executeWithoutResult(status -> {
            // transactional work here
        });
    }
}
Also silently ignored

@Transactional on a private, final, static or protected method. CGLIB proxies work by subclassing, and none of those can be overridden. No warning is produced.

Isolation levels

LevelPreventsCost
READ_UNCOMMITTEDnothing—
READ_COMMITTEDdirty readslow — PostgreSQL/Oracle default
REPEATABLE_READ+ non-repeatable readsmedium — MySQL InnoDB default
SERIALIZABLE+ phantomshigh, with retries under contention
DEFAULTwhatever the database doesthe right choice 95% of the time

Before raising the isolation level, ask whether optimistic locking solves the problem — it usually does, at a fraction of the cost.

Optimistic vs pessimistic locking

optimistic — the default choice
@Entity
public class Book {
    @Version
    private int version;      // Hibernate adds "AND version = ?" to every UPDATE
}

@Transactional
public void changePrice(Long id, BigDecimal newPrice) {
    Book book = bookRepository.findById(id).orElseThrow();
    book.setPrice(newPrice);
    // on commit: UPDATE book SET price=?, version=version+1 WHERE id=? AND version=?
    // 0 rows updated → OptimisticLockingFailureException → map to HTTP 409
}
pessimistic — when a retry is unacceptable
public interface StockRepository extends JpaRepository<Stock, Long> {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("SELECT s FROM Stock s WHERE s.bookId = :bookId")
    Optional<Stock> findForUpdate(@Param("bookId") Long bookId);
}

Pessimistic locks issue SELECT … FOR UPDATE and serialise every concurrent writer. Always pair with a short transaction and a lock timeout, or one slow request blocks all the others.

Timeouts

bound every transaction
@Transactional(timeout = 10)                  // seconds
public void reconcile() { }
application.yml — a global default
spring:
  transaction:
    default-timeout: 30s
  jpa:
    properties:
      jakarta.persistence.query.timeout: 15000    # milliseconds

Transactional events

Publishing an event inside a transaction and reacting to it only after commit is the clean way to trigger side effects such as emails, cache eviction or messages.

publishing and listening
@Service
public class OrderService {

    private final ApplicationEventPublisher events;

    @Transactional
    public Order place(PlaceOrderCommand command) {
        Order order = orders.save(new Order(command));
        events.publishEvent(new OrderPlacedEvent(order.getId(), order.getTotal()));
        return order;
    }
}

@Component
public class OrderNotifier {

    /* Runs only if the transaction commits. If it rolls back, no email is sent. */
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void onOrderPlaced(OrderPlacedEvent event) {
        mailer.sendConfirmation(event.orderId());
    }
}
Why this beats calling the mailer directly

A direct call sends the email even if the transaction later rolls back — the customer gets a confirmation for an order that does not exist. AFTER_COMMIT makes that impossible. Note that database writes inside an AFTER_COMMIT listener need REQUIRES_NEW, since the original transaction is already finished.

Verifying it actually works

application.yml — dev only
logging:
  level:
    org.springframework.transaction.interceptor: TRACE
    org.springframework.orm.jpa.JpaTransactionManager: DEBUG
what a working boundary looks like
TRACE o.s.t.i.TransactionInterceptor : Getting transaction for [com.bitsnippets.bookstore.order.OrderService.place]
DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(...)]
TRACE o.s.t.i.TransactionInterceptor : Completing transaction for [com.bitsnippets.bookstore.order.OrderService.place]
DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit

If the "Getting transaction for" line is absent, your annotation is not being applied — self-invocation, wrong visibility, or the class is not a Spring bean.

Checklist

  • Boundaries in the service layer, never in controllers or repositories.
  • Domain exceptions extend RuntimeException.
  • No self-invocation of annotated methods.
  • readOnly = true on every read-only path.
  • No HTTP calls, file I/O or message publishing inside a transaction — use AFTER_COMMIT.
  • A timeout on every transaction.
  • @Version before reaching for SERIALIZABLE.
  • Transactions kept short: open late, commit early.

A @Transactional method throws a checked IOException. What happens to the data written so far?

Spring's default rule rolls back only on RuntimeException and Error — inherited from EJB conventions. A checked exception commits the work and then propagates, which is almost never what you want. Fix it with rollbackFor = Exception.class, or by using unchecked exceptions.