Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 39 ยท Configuration and Sessions

Entity States and the Persistence Context

Understand the four Hibernate entity states, the persistence context as first-level cache, how persist, merge, detach, clear and refresh move objects between states.

Every entity object in a Hibernate application is in one of four states, and the state decides what happens when you change it. A brand-new object is not saved by changing it; a loaded object is saved by changing it; an object from a closed session is ignored. If you understand the states and the persistence context that defines them, most of Hibernate's "magic" and most of its surprising exceptions become predictable.

This lesson defines the states, shows the transitions, and explains the first-level cache. Real Hibernate code is read-only; the stand-ins are plain Java models of the same rules.

The four states

State Has an identifier? Tracked by a session? In the database?
Transient (new) Usually not No No
Managed (persistent) Yes Yes Yes (or will be at flush)
Detached Yes No (session closed or evicted) Yes
Removed Yes Yes, scheduled for delete Until flush
stateDiagram-v2
    [*] --> Transient: new Book()
    Transient --> Managed: persist()
    Managed --> Detached: close(), clear(), detach()
    Detached --> Managed: merge() (returns a managed copy)
    Managed --> Removed: remove()
    Removed --> Managed: persist()
    Removed --> [*]: flush / commit
    Managed --> Managed: find(), refresh()

The lifecycle of an entity instance.

  • Transient. You created it with new. Hibernate knows nothing about it. Changes are not saved.
  • Managed. It is attached to an open session. Hibernate snapshots its state and writes any change at flush time.
  • Detached. It has an identifier and a row exists, but the session that managed it is gone (closed, cleared, or the object was detached). Changes are not tracked.
  • Removed. It is scheduled for deletion at flush.
Java
sessionFactory.inTransaction(session -> {
    Book book = new Book("Refactoring", 448);   // transient
    session.persist(book);                      // managed
    book.setPages(450);                         // tracked: part of the INSERT/UPDATE at flush
    session.detach(book);                       // detached: further changes are ignored
    book.setPages(999);                         // lost
});

The persistence context

The persistence context is the set of managed entities of one session. It is also called the first-level cache, and it is always on. It guarantees two things.

  1. Identity. Within one session there is at most one managed object for each row (entity type + ID). Loading the same row twice returns the same instance, so == works inside a session.
  2. Change tracking. Hibernate keeps a snapshot of every managed object, so it can find what changed at flush time.
Java
Book a = session.find(Book.class, 1L);   // SELECT
Book b = session.find(Book.class, 1L);   // no SQL: served from the persistence context
assert a == b;

Across sessions there is no such guarantee: two sessions load two different instances for the same row. Use equals/hashCode based on a business key or ID for comparison across sessions (see Entity mapping).

Moving between states

Call Effect
persist(e) Transient to managed. Cascades to relationships marked for it.
find / query results The returned entities are managed.
merge(e) Copies a detached (or transient) object's state onto a managed instance and returns it. The argument itself stays as it was.
remove(e) Managed to removed. Detached input throws.
detach(e) One entity leaves the session.
clear() All entities leave the session (all become detached).
evict(e) Hibernate's older name for detach.
refresh(e) Reloads state from the database, overwriting unflushed changes.
contains(e) Is this instance currently managed?

Clearing the session (session.clear()) after a flush is a standard trick in big batch jobs: it frees memory so the session does not hold a million entities.

  • detached entity passed to persist: you called persist on an object that already has an ID from an earlier session. Use merge, or find it in the current session.
  • LazyInitializationException: you touched a lazy association after the session closed. The object is detached and cannot fetch more. See lazy loading.
  • NonUniqueObjectException / duplicate key in the session: two different instances with the same ID in one persistence context, for example after merge mistakes. Use the instance merge returns.
  • Lost updates: you changed a detached object and forgot to merge it.

Stand-in: the state machine

This stand-in models the four states with an enum and allows only the legal transitions, throwing for the others. The messages are inspired by Hibernate's, but this is just plain Java.

Java Stand-in: legal transitions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in: the first-level cache

Here is the persistence context's two guarantees in miniature: one instance per ID inside a session, and a different instance in another session. The program also counts the SQL statements: the repeated find costs none.

Java Stand-in: identity inside a session

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An object created with new and never passed to the session is:

    Hibernate does not know about it, so it is transient and its changes are not saved.
  2. 2. What does the persistence context guarantee inside one session?

    That is the identity guarantee, and it is why a second find for the same ID needs no SQL.
  3. 3. You loaded a Book in a closed session and changed it. What must you do to save the change?

    The object is detached; merge copies its state onto a managed instance.
  4. 4. What does session.clear() do?

    It empties the persistence context; the entities become detached. It does not touch the database.
  5. 5. What is the likely cause of 'detached entity passed to persist'?

    persist is for new objects. Existing ones need find or merge.

Summary

  • Entities are transient, managed, detached or removed; only managed ones are tracked and saved automatically.
  • The persistence context (first-level cache) gives one instance per row per session and the snapshots for dirty checking.
  • persist, merge, remove, detach, clear, refresh and contains move objects between states.
  • merge returns the managed copy; the object you pass in does not become managed.
  • Most mapping exceptions (detached entity to persist, lazy initialization) are state errors.

Next: Flush and Dirty Checking