JPA and Hibernate · core
Entity states, flush and dirty checking
A managed entity is tracked by the persistence context. At commit Hibernate compares it with a snapshot and writes changes. An entity outside a transaction is detached and is not saved.
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
- States: transient (new, unknown to Hibernate), managed (in the persistence context), detached (context closed), removed.
- The persistence context is a per-transaction map of id to entity (the first-level cache) plus snapshots for dirty checking.
- Writes are queued and sent at flush: before commit, before a query that touches those tables (AUTO flush mode), or on
flush(). - Spring Data
save():persistif the entity is new, otherwisemerge. New means the id (or version) is null. With ids set in code, save runsmerge, which does a SELECT first. saveAndFlush()sends the SQL now. Useful to hit a constraint immediately. It does not commit.- Hibernate 7 removed the old
Session.save,updateandsaveOrUpdate. Usepersistandmerge. - A @Transactional method that loads an entity and changes it needs no save call: dirty checking writes the change at commit.
- Without a transaction on the service method,
findByIdreturns a detached entity and the change is lost. Called from a @Transactional caller it works: behaviour depends on the caller, which is a smell. Make write methods transactional. By default Hibernate updates every column;@DynamicUpdatesends only changed columns.@Transactional(readOnly = true)skips snapshots and flushing.
The red pen
Common traps: mistake → fix
Mistake: I must call save() after every change
Fix: inside a transaction, dirty checking saves managed entities.
Mistake: save() always inserts
Fix: it inserts if new, merges otherwise.
Mistake: saveAndFlush commits
Fix: it only sends the SQL; commit happens at the end of the transaction.
Easy to hard
Questions interviewers ask, easy to hard
- Explain transient, managed, detached and removed.
- save() versus saveAndFlush()?
- A reviewer says the update has no save call. Who is right?
- Why does an update method without @Transactional silently do nothing?
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.