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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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 = trueis 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:
recordAttemptwith REQUIRES_NEW called onthisis 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
- Which propagation options do you use?
- What does readOnly = true really do?
- Which exceptions roll back by default?
- Failed payments leave no audit row. Why?
- Refunds say completed but the money never left. Why did nothing roll back?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.