Video in progress

Strong Middle 🌱 Spring

How are transaction isolation levels set in Spring, and what's the default?

You set them with @Transactional(isolation = ...); the default is Isolation.DEFAULT, meaning the database's own default: READ COMMITTED in PostgreSQL and Oracle, REPEATABLE READ in MySQL InnoDB. The higher the level, the fewer anomalies, but the more locks and retries.

📖 Answer

@Transactional(isolation = Isolation.REPEATABLE_READ)
public Report monthlyReport(YearMonth m) { ... } // several queries should see the same "snapshot"

Anomalies in short:

Level Dirty read Non-repeatable read Phantom
READ COMMITTED no yes yes
REPEATABLE READ no no yes per the standard (not in PostgreSQL)
SERIALIZABLE no no no

In practice:

  • READ COMMITTED allows "lost updates": two transactions read a balance and both write it. Rather than raising isolation, an atomic UPDATE, @Version or SELECT ... FOR UPDATE is often the better fix.
  • In PostgreSQL, REPEATABLE READ and SERIALIZABLE throw could not serialize access on conflict — the app must be ready to retry the whole transaction.
  • Isolation is set at the start of the transaction. If an inner @Transactional(isolation=...) joins an open transaction via REQUIRED, its level isn't applied (it's silently ignored unless validateExistingTransaction is enabled).
  • For reports, REPEATABLE READ + readOnly gives consistent results and doesn't block writes (MVCC).