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.
The mechanism
Spring does not modify your bytecode. It wraps your bean in a proxy that runs the transaction management around your method:
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
@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));
}
}
| Layer | Transactional? | Why |
|---|---|---|
| Controller | No | The boundary would then include JSON serialisation and HTTP concerns |
| Service | Yes | This is the unit of business work — the correct atomicity boundary |
| Repository | Inherited | Spring 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.
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.
| Propagation | Transaction exists | No transaction | Use for |
|---|---|---|---|
REQUIRED (default) | join it | start one | Almost everything |
REQUIRES_NEW | suspend it, start a new one | start one | Audit rows that must survive a rollback |
SUPPORTS | join it | run without one | Read methods callable either way |
NOT_SUPPORTED | suspend it | run without one | Long non-transactional work |
MANDATORY | join it | throw | Enforcing that a caller opened one |
NEVER | throw | run without one | Rare |
NESTED | savepoint | start one | Partial rollback (JDBC only, not JPA) |
@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()));
}
}
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
// 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
@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:
- Make
processOneREQUIRES_NEW, so its failure is isolated. - Move the loop outside the transaction and start one per item.
Self-invocation: the number one bug
@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()
}
}
// 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
});
}
}
@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
| Level | Prevents | Cost |
|---|---|---|
READ_UNCOMMITTED | nothing | — |
READ_COMMITTED | dirty reads | low — PostgreSQL/Oracle default |
REPEATABLE_READ | + non-repeatable reads | medium — MySQL InnoDB default |
SERIALIZABLE | + phantoms | high, with retries under contention |
DEFAULT | whatever the database does | the 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
@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
}
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
@Transactional(timeout = 10) // seconds
public void reconcile() { }
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.
@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());
}
}
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
logging:
level:
org.springframework.transaction.interceptor: TRACE
org.springframework.orm.jpa.JpaTransactionManager: DEBUG
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 = trueon every read-only path.- No HTTP calls, file I/O or message publishing inside a transaction — use
AFTER_COMMIT. - A timeout on every transaction.
@Versionbefore reaching forSERIALIZABLE.- 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.