Skip to the page

JPA and Hibernate · mid

Transaction propagation and rollback rules

By default only unchecked exceptions roll back. REQUIRES_NEW needs a call through the proxy. Keep transactions short and never call remote services inside them.

The notes

What you must know

  • REQUIRED (default): join the current transaction or start one. REQUIRES_NEW: suspend the current one and run a new one on a second connection; it commits or rolls back on its own.
  • readOnly = true is a hint: Hibernate sets flush mode to MANUAL and skips dirty-checking snapshots. It is not a guard against writes on every database.
  • Rollback by default: only for RuntimeException and Error. A checked exception commits unless rollbackFor = Exception.class.
  • An inner REQUIRED method that throws marks the shared transaction rollback-only. If the outer method catches it and carries on, the commit fails with UnexpectedRollbackException.
  • Put @Transactional on service methods (one use case), keep transactions short, never span remote calls.
  • Audit row lost: recordAttempt with REQUIRES_NEW called on this is never applied (self-invocation), so it rolls back with the payment. Move it to another bean.
  • With REQUIRES_NEW each call holds two connections at once. With a small pool every thread can hold one and wait for another: a pool deadlock.
  • Call the gateway outside the transaction. Or use @TransactionalEventListener(phase = AFTER_COMPLETION) to write the audit once the outcome is known. Refund marked completed but the bank call failed: the exception was checked, so the transaction committed. Better design: states (PENDING, then the bank call outside the transaction with an idempotency key, then COMPLETED or FAILED).

The red pen

Common traps: mistake → fix

  • Mistake: @Transactional always rolls back on exceptions

    Fix: not on checked ones.

  • Mistake: REQUIRES_NEW works from the same class

    Fix: the call must go through the proxy.

  • Mistake: A catch block keeps the transaction healthy

    Fix: the inner call may already have marked it rollback-only.

Easy to hard

Questions interviewers ask, easy to hard

  1. Which propagation options do you use?
  2. What does readOnly = true really do?
  3. Which exceptions roll back by default?
  4. Failed payments leave no audit row. Why?
  5. Refunds say completed but the money never left. Why did nothing roll back?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview