Repaso
EspaƱol
Spring, JPA & Java WebIntermediateSPR-14

What does @Transactional do?

Options

  1. It makes the method run faster by caching the results
  2. It wraps the method in a transaction: commit or rollback (Correct option)
  3. It makes the method run asynchronously in another thread
  4. 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.

Key terms

Practice this question in Repaso