Video in progress

Middle 🌱 Spring

Which exceptions make @Transactional roll back, and which don't?

By default only unchecked ones (RuntimeException and Error) cause a rollback. On a checked exception (IOException or your own class extending Exception) the transaction commits. You can change this with rollbackFor.

📖 Answer

This rule is a leftover from the EJB days: a checked exception is a "business situation", an unchecked one is an "unexpected error".

@Transactional
public void importFile(Path file) throws IOException {
    rows.save(header);
    Files.readAllLines(file); // IOException
    // the transaction COMMITS — the header stays saved!
}

The fix:

@Transactional(rollbackFor = Exception.class)
public void importFile(Path file) throws IOException { ... }

Two more traps:

Swallowing the exception:

try { payments.charge(o); }
catch (PaymentException e) { log.warn("...", e); } // Spring never sees the error -> commit

The rollback-only flag: if an inner @Transactional (REQUIRED) method throws a RuntimeException, the transaction is marked "rollback-only". Even if the outer method catches the exception and carries on, you get UnexpectedRollbackException on commit. This is where a lot of people get confused.

That's why many teams make their domain exceptions extend RuntimeException — then the default just does the right thing.