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)
sequenceDiagram
participant C as RenewalController
participant P as RenewalService proxy
participant M as PlatformTransactionManager
participant S as RenewalService
participant R as Repositories
C->>P: renew("Leo", 1, 79)
P->>M: getTransaction() (BEGIN, connection bound to thread)
P->>S: renew(...)
S->>R: extend() and debit()
alt returns normally, or checked exception
P->>M: commit()
else RuntimeException / Error
P->>M: rollback()
end
P-->>C: result or exceptionKey pieces
PlatformTransactionManager: the abstraction (DataSourceTransactionManager/JdbcTransactionManager,JpaTransactionManager,JtaTransactionManager)@EnableTransactionManagement: enables@Transactionalin plain Spring; Spring Boot does it on its own@Transactionalon a method or class:readOnly,isolation,timeout,propagation,rollbackFor,noRollbackForTransactionTemplateandTransactionStatus.setRollbackOnly(): programmatic transactions- In tests,
@Transactionalrolls back at the end;@Commitor@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
RuntimeExceptionandError; on checked exceptions it commits @Transactionalworks through a proxy: it only intercepts calls coming from outside, to public methods@Transactionalon the class applies to all its public methods; on a method, it overrides the class one- Isolation levels:
READ_UNCOMMITTED,READ_COMMITTED,REPEATABLE_READ,SERIALIZABLEandDEFAULT(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@Transactionalon aprivatemethod (or a class without a proxy) is ignoredreadOnly = trueis 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