Skip to the page

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.

The 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(): persist if the entity is new, otherwise merge. New means the id (or version) is null. With ids set in code, save runs merge, 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, update and saveOrUpdate. Use persist and merge.
  • 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, findById returns 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; @DynamicUpdate sends 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

  1. Explain transient, managed, detached and removed.
  2. save() versus saveAndFlush()?
  3. A reviewer says the update has no save call. Who is right?
  4. Why does an update method without @Transactional silently do nothing?

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