Skip to the page

JPA and Hibernate · Concept

Entity states and save() vs saveAndFlush()

The 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

  1. When does Hibernate actually send the INSERT?
  2. What does save() do with an entity that already has an id?
  3. persist or merge: what's the difference?
  4. When would you really need saveAndFlush()?
  5. 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(): persist if the entity is new, otherwise merge. "New" means the id (or version) is null. With ids assigned in code (UUIDs), save() runs a SELECT and then merges, unless the entity implements Persistable.
  • 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, update and saveOrUpdate; use persist and merge.

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 voice

Practise 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.

Start your free interview