Video in progress

Strong Middle 🧭 Design patterns

How do the Unit of Work and Identity Map patterns work in Hibernate's persistence context, and what do they mean in practice?

The session keeps exactly one instance of each entity it loaded, per id (Identity Map), and writes changes to the database not immediately but as one batch at flush time (Unit of Work). That is why a change gets saved even if you never call save(), and why memory grows in a big batch.

📖 Answer

Inside a single transaction:

@Transactional
public void rename(long id, String name) {
    Course a = em.find(Course.class, id);   // SELECT
    Course b = em.find(Course.class, id);   // no SELECT, the same object
    assert a == b;
    a.setTitle(name);                       // no save(), but an UPDATE goes out on commit
}

Thanks to the Identity Map there is one object in memory per row, so two copies can never contradict each other. The Unit of Work keeps a snapshot of every managed entity as it was when loaded. At flush time, dirty checking compares the snapshot with the current state and issues the needed INSERT/UPDATE/DELETE statements in the right order.

What this means in practice:

  • You don't have to call repo.save(entity) for a managed entity. The flip side: if you modify an entity "just to read it", that change gets saved silently too.
  • Flush doesn't happen only on commit: with FlushMode.AUTO it can also happen before a JPQL query. So a constraint violation sometimes shows up not on the save line but on the next query.
  • Until the persistence context is cleared, every entity and its snapshot stays in memory. In an import of a million rows, if you don't do em.flush(); em.clear(); every 500–1000 rows, you end up with an OOM.
  • In read-only queries, @Transactional(readOnly = true) means Hibernate keeps no snapshot and does no dirty checking, which saves both memory and CPU.