Cheatsheet

Transactions

Key idea

A transaction groups several operations into one atomic unit: either all of them are committed or none. In Spring you declare it with `@Transactional`; a proxy begins the transaction through the `PlatformTransactionManager`, calls your method and commits, or rolls back if an unchecked exception comes out.

Diagram (UML)

ApplicationContextAthleteRenewalControllerRenewalService (proxy)RenewalServicePlatformTransactionManagerWalletRepository30MembershipRepositoryH2

Key pieces

  • PlatformTransactionManager: the abstraction (DataSourceTransactionManager/JdbcTransactionManager, JpaTransactionManager, JtaTransactionManager)
  • @EnableTransactionManagement: enables @Transactional in plain Spring; Spring Boot does it on its own
  • @Transactional on a method or class: readOnly, isolation, timeout, propagation, rollbackFor, noRollbackFor
  • TransactionTemplate and TransactionStatus.setRollbackOnly(): programmatic transactions
  • In tests, @Transactional rolls back at the end; @Commit or @Rollback(false) to commit

RenewalService.java

@Transactional // the proxy opens a transaction, calls this method, then commits or rolls back
public void renew(String athlete, int months, BigDecimal price) {
    memberships.extend(athlete, months);   // 1st write
    wallets.debit(athlete, price);         // 2nd write: may throw InsufficientFundsException
}

Remember for the exam

  • ACID: atomicity, consistency, isolation and durability
  • By default rollback happens on RuntimeException and Error; on checked exceptions it commits
  • @Transactional works through a proxy: it only intercepts calls coming from outside, to public methods
  • @Transactional on the class applies to all its public methods; on a method, it overrides the class one
  • Isolation levels: READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE and DEFAULT (the database's)
  • Phenomena they prevent: dirty reads, non-repeatable reads and phantom reads
  • Repositories use the current transaction's connection: the manager binds it to the thread

Exam traps

  • A checked exception does not roll the transaction back: what was written is committed (unless rollbackFor)
  • this.method() inside the same class skips the proxy: no transaction
  • @Transactional on a private method (or a class without a proxy) is ignored
  • readOnly = true is a hint for the manager and the driver; it doesn't prevent writes in every case
  • Catching the exception inside the transactional method and not rethrowing it makes it commit

← Transactions · Run it