Easy java spring

What does @Transactional do?

The 30 second answer

It runs the method inside a database transaction: Spring starts a transaction before the method, commits if it returns normally, and rolls back if it throws a RuntimeException or Error. By default a checked exception does not roll back unless I set rollbackFor. It works through a proxy, so it only applies to public calls coming from another bean; calling the method from inside the same class skips it. I put it on service methods, not controllers.

<!-- level: 1 --> <!-- must_know: true -->

@Service
public class TransferService {
    @Transactional
    public void transfer(long from, long to, BigDecimal amount) {
        accounts.debit(from, amount);
        accounts.credit(to, amount);   // if this throws, the debit is rolled back
    }
}

What to know:

  • How it works: Spring wraps the bean in a proxy. The proxy opens a transaction, calls your method, and commits or rolls back.
  • Rollback rules: by default, Spring rolls back for RuntimeException and Error and not for checked exceptions. Use @Transactional(rollbackFor = Exception.class) to change that.
  • Self-invocation: calling a @Transactional method from another method of the same class bypasses the proxy, so no transaction starts. This is the classic interview trap.
  • Where: on service methods that group several writes. readOnly = true is a useful hint for read-only methods.
  • Propagation: the default REQUIRED joins an existing transaction or starts a new one; REQUIRES_NEW always starts a separate one.

The production version of this question is An exception was thrown but the transaction still committed. Why?.

Sources (2)
  1. Spring Framework: Using @Transactionaldocs.spring.io
  2. Spring Framework: Rolling back a declarative transactiondocs.spring.io