BBackend CourseLeroy Labs
0/0
Search the course

@Transactional in depth: propagation, readOnly, rollback rules & traps

How Spring's transaction proxy works, REQUIRED vs REQUIRES_NEW vs MANDATORY, readOnly optimizations, checked-exception rollback, self-invocation, and controller-level transactions.

● advancedSpring-Boot-StoreHostel-Web-AppReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

How it works

@Transactional is an aspect. The proxy wraps your call like this:

// what the proxy does, roughly
TransactionStatus tx = txManager.getTransaction(definition);   // begin (or join)
try {
    Object result = target.method(args);
    txManager.commit(tx);                                        // flush + COMMIT
    return result;
} catch (RuntimeException | Error e) {
    txManager.rollback(tx);
    throw e;
}

The transaction is bound to the current thread, together with one JDBC connection from the pool.

Propagation

Propagation Behaviour Use
REQUIRED (default) Join the existing transaction, or start one Almost everything
REQUIRES_NEW Suspend the current one and run a separate transaction Audit or log rows that must persist even if the caller rolls back
MANDATORY Throw if there’s no active transaction A method that must only run as part of a bigger unit
SUPPORTS Join if present, otherwise run without one Rare
NOT_SUPPORTED Suspend the transaction and run without one Long non-DB work
NEVER Throw if a transaction exists Rare
NESTED A savepoint inside the current transaction Partial rollback

readOnly = true

@Transactional(readOnly = true)
public Page<BookingSummaryDto> myBookings(UUID studentId, Pageable p) { /* ... */ }
  • Hibernate skips dirty checking and snapshots, which saves CPU and memory.
  • The JDBC connection is flagged read-only, so a routing DataSource can send it to a replica.
  • It documents intent.

Rollback rules

By default Spring rolls back on RuntimeException and Error only. A checked exception commits, which surprises a lot of people. Override it with @Transactional(rollbackFor = Exception.class).

In your projects

SperoTek (in dev)ledger/application/DefaultPostingEngine.java

SperoTek uses propagation = MANDATORY for internal steps that must never run alone. If someone calls the method outside the posting transaction, it fails loudly rather than committing half a journal.

Hostel-Web-AppBookingService · NotificationService

@Transactional on writes and @Transactional(readOnly = true) on reads (myBookings, getMyNotifications). This is the textbook split.

IR3D (Kontentt)413 x @Transactional

At IR3D’s scale, transaction boundaries are the architecture. The money paths use one transaction for the wallet lock plus the ledger postings. External calls (Paystack) happen outside it, via after-commit events.

Spring-Boot-Storecontrollers/CartController.java · UserController.java

@Transactional sits on controller methods. It works, but:

  • the transaction (and its DB connection) is held during JSON parsing and serialisation;
  • the business unit of work is defined in the web layer;
  • the logic can’t be reused from a scheduler or another caller.

Move it to CartService.addItem(...).

The traps

Alternatives

  • TransactionTemplate gives programmatic control: tx.execute(status -> ...). It is useful inside loops, for example committing per batch in RM’s SoftDeletePurgeScheduler.
  • Batching large jobs. Commit every N rows so one huge transaction doesn’t hold locks or bloat WAL.

Check yourself

1. A @Transactional method throws a checked IOException. Default behavior?
2. Audit row must persist even if the business transaction rolls back. Propagation?
3. What does readOnly=true save in Hibernate?