Difficulty: Advanced
How does @Transactional work internally? Explain propagation, default rollback behaviour, and why a transactional method sometimes has no effect.
Money transfer is the classic story. You debit account A, then credit account B. If the credit fails halfway, you must undo the debit or money vanishes. A transaction groups both steps so they either fully succeed or fully roll back. @Transactional lets you declare that with an annotation instead of writing begin, commit, and rollback yourself. The real skill in interviews is knowing how it works, because the failure modes come from the mechanism.
It is implemented with AOP proxies. When Spring finds a bean with @Transactional, it wraps it in a proxy. A call from outside goes through the proxy, which asks the PlatformTransactionManager to start a transaction, invokes your real method, then commits if it returned normally or rolls back if it threw. Your code never sees this. That single fact explains the biggest pitfall: self-invocation. If method A in a bean calls method B in the same bean, this.B() bypasses the proxy, so B's @Transactional annotation is ignored. The same goes for @Async and caching annotations. The fixes: move B into another bean, inject the bean into itself carefully, use TransactionTemplate for programmatic control, or restructure the flow. Related pitfalls: @Transactional on private or final methods does nothing with proxy-based AOP, and it only applies to Spring-managed beans, not objects you create with new.
Rollback rules trip up many candidates. By default Spring rolls back only for unchecked exceptions, meaning RuntimeException and Error. A checked exception such as IOException or your own custom checked exception commits the transaction anyway. To roll back on checked exceptions you write @Transactional(rollbackFor = Exception.class). Another silent trap: if you catch the exception inside the transactional method and swallow it, the proxy never sees a failure and commits.
Propagation describes what happens when a transactional method is called while a transaction already exists. REQUIRED, the default, joins the existing transaction or creates one if none exists. REQUIRES_NEW suspends the current transaction and starts a fresh independent one, useful for audit logging that must be saved even if the main operation rolls back. SUPPORTS runs in a transaction if one exists, otherwise non-transactionally. NOT_SUPPORTED suspends any transaction. MANDATORY requires an existing transaction or throws. NEVER throws if one exists. NESTED uses a savepoint inside the existing transaction, so an inner failure can roll back to the savepoint, though it requires JDBC savepoint support and does not work with plain JPA in all providers.
A subtle REQUIRED gotcha: if an inner method joined the outer transaction and throws a runtime exception, the transaction is marked rollback-only. Even if the outer method catches the exception, the eventual commit fails with UnexpectedRollbackException. This surprises many teams.
Other attributes worth naming: readOnly = true hints for optimisation and prevents flush in Hibernate, isolation controls visibility between concurrent transactions, and timeout bounds duration. Keep transactions short, never call remote HTTP services inside one because they hold database connections, and place @Transactional on the service layer, not on controllers or repositories.
@Service
@RequiredArgsConstructor
public class TransferService {
private final AccountRepository accounts;
private final AuditService audit; // separate bean on purpose
@Transactional(rollbackFor = Exception.class) // also roll back on checked exceptions
public void transfer(Long from, Long to, BigDecimal amt) throws InsufficientFundsException {
Account a = accounts.findById(from).orElseThrow();
Account b = accounts.findById(to).orElseThrow();
a.debit(amt); // may throw checked exception
b.credit(amt);
audit.record(from, to, amt); // goes through proxy of AuditService
}
public void bulkTransfer(List<Transfer> list) {
for (Transfer t : list) {
this.transfer(t.from(), t.to(), t.amount()); // BUG: self-call bypasses proxy
}
}
}
@Service
class AuditService {
@Transactional(propagation = Propagation.REQUIRES_NEW) // commits even if transfer rolls back
public void record(Long from, Long to, BigDecimal amt) { /* save audit row */ }
}
bulkTransfer calls transfer via this, so no transaction starts. AuditService uses REQUIRES_NEW so its row survives a rollback of the outer transfer.
Transactional, Propagation, Rollback, Self-Invocation