What does @Transactional do?
Options
- It makes the method run faster by caching the results
- It wraps the method in a transaction: commit or rollback (Correct option)
- It makes the method run asynchronously in another thread
- It encrypts the data that the method reads and writes
Answer
Wraps the method in a database transaction: commit if it completes, roll back if a RuntimeException (or Error) escapes
Why
A transaction groups several database operations so they all succeed or all fail (ACID). @Transactional does this declaratively: Spring starts a transaction before the method and commits after it.
Default rollback rule: only for unchecked exceptions (RuntimeException, Error). A checked exception does NOT roll back unless you write @Transactional(rollbackFor = Exception.class).
Place it on service methods (the unit of work), not on controllers or repositories.
@Transactional
public void transfer(Long from, Long to, BigDecimal amount) {
accounts.withdraw(from, amount);
accounts.deposit(to, amount); // if this throws, the withdraw is undone
}Remember
@Transactional: commit on success, rollback on RuntimeException by default.