Video in progress

Junior 🌱 Spring

What does @Transactional do?

It runs the method in a single transaction: if everything goes fine it commits, if a RuntimeException is thrown it rolls back. Data is never left half-saved.

📖 Answer

The classic example is a money transfer:

@Service
public class TransferService {
    @Transactional
    public void transfer(long from, long to, BigDecimal amount) {
        accounts.withdraw(from, amount);
        accounts.deposit(to, amount); // if this fails, the withdrawal is undone too
    }
}

Without a transaction, if the first step got saved and the second one failed, the money would just vanish.

Under the hood Spring builds a proxy around the class. When the method is called, the proxy opens a transaction, commits when the method finishes, and rolls back on an exception.

Mistakes beginners often make:

  • putting it on a private method — the proxy doesn't see it;
  • calling another method from inside the same class — the proxy is bypassed;
  • catching the exception and "swallowing" it — Spring never learns there was an error and commits.