JPA and Hibernate · Concept
Entity states and save() vs saveAndFlush()
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
Explain the life of a JPA entity: transient, managed, detached and removed. And what's the difference between save() and saveAndFlush() in Spring Data?
Then
Follow-ups the interviewer asks next
- When does Hibernate actually send the INSERT?
- What does
save()do with an entity that already has an id? persistormerge: what's the difference?- When would you really need
saveAndFlush()? - What is the persistence context?
The answer
What a strong answer covers
- Transient: just created with
new, unknown to Hibernate. Managed: in the persistence context (after persist, find or a query); changes are tracked. Detached: was managed, but the context closed (the transaction ended) or it was detached or cleared. Removed: scheduled for delete. - The persistence context is a per-transaction map of id → entity (the first-level cache) plus snapshots used 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 assigned in code (UUIDs),save()runs a SELECT and then merges, unless the entity implementsPersistable. saveAndFlush()sends the SQL now: useful to hit a constraint immediately (and handle it) or before native SQL in the same transaction. It doesn't commit.- Hibernate 7 removed the old
Session.save,updateandsaveOrUpdate; usepersistandmerge.
The red pen
Common traps
Avoid:"saveAndFlush commits"; "save() runs the INSERT immediately"; not knowing about the extra SELECT for assigned ids.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.