Skip to content
javahacks.dev
Hibernate

Hibernate Entity States and the Persistence Context

The four Hibernate entity states, transient, managed, detached and removed, how the persistence context tracks them and how persist and merge move them.

7 min read
Summarize in AI
Flat illustration of an entity class mapped to a database table, with the Hibernate, MariaDB, Liquibase, MySQL and Spring Boot logos.

Most confusing Hibernate behaviour is explained by one question: in what state is this object? The state decides whether a change is saved, whether a lazy field loads and which exception you get. This uses Hibernate 7 and Jakarta Persistence 3.2 on JDK 25. The mapping basics are in JPA and Hibernate.

The four states

StateMeaningHas identityTracked
TransientNew object, not known to the database or any contextNot yetNo
Managed (persistent)Associated with an open persistence contextYesYes
DetachedWas managed, context closed or entity evictedYesNo
RemovedScheduled for deletion at flushYesYes, until flush
java
Customer c = new Customer("ada");     // transient
em.persist(c);                         // managed: INSERT is scheduled
c.setName("Ada Lovelace");             // managed: change tracked
// commit or flush: INSERT, then UPDATE if needed
em.detach(c);                          // detached: changes no longer saved

The persistence context

The persistence context is a first level cache and a unit of work. It holds each managed entity once per identity, so loading the same row twice in one context returns the same object. At flush it compares the entities with the snapshots taken when they were loaded and issues INSERT, UPDATE and DELETE. That comparison is dirty checking. The cache and flush timing are in the first level cache.

In Spring, @Transactional creates a persistence context for the duration of the transaction. After the method returns, it closes, and every entity loaded becomes detached.

Operations and transitions

CallFromToNotes
persist(e)TransientManagedFails for detached with PersistentObjectException
find, queryDatabaseManaged
merge(e)Detached or transientReturns managed copyThe argument is not made managed
remove(e)ManagedRemovedFails for detached
detach(e), clear()ManagedDetachedPending changes lost unless flushed
refresh(e)ManagedManagedReloads from the database

The error in detached entity passed to persist is calling persist on an object that already has an id and has left its context. The fix is merge, with one subtlety:

java
Customer detached = loadOutsideTransaction();
detached.setName("New");
Customer managed = em.merge(detached);   // use this one
managed == detached;                      // false

merge copies the state of the argument onto a managed instance, loading it if needed, and returns that instance. Later changes must be made to the returned object. With Spring Data, save() calls persist for new entities and merge otherwise.

Why "no save needed" works

java
@Transactional
void rename(long id, String name) {
    Customer c = repository.findById(id).orElseThrow();   // managed
    c.setName(name);                                       // no save call
}                                                          // flush at commit writes UPDATE

The entity is managed, so the change is written. The same code outside a transaction, or on a detached entity, would do nothing. This surprises people from the other direction too: an accidental setter call on a managed entity inside a transaction updates the database.

Exceptions as state hints

ExceptionUsually means
LazyInitializationExceptionEntity is detached and a lazy field was touched, see that fix
PersistentObjectException: detached entity passed to persistpersist on a detached entity
TransientObjectException / TransientPropertyValueExceptionA managed entity points at a transient one
StaleObjectStateExceptionA row changed since it was loaded

Walk one entity through every state

The four states are easiest to learn by asking the persistence context, with the SQL log on. This runner creates an Author, saves it, leaves the transaction, changes it, merges it and removes it. It uses Hibernate ORM 7.2.25.Final in Spring Boot 4.0.9.

java
tx.executeWithoutResult(s -> {
    Author a1 = new Author("Ada");
    System.out.println("new:       managed=" + em.contains(a1) + " id=" + a1.getId());
    em.persist(a1);
    System.out.println("persisted: managed=" + em.contains(a1) + " id=" + a1.getId());
    detached[0] = a1;
});
System.out.println("after commit: managed? " + tx.execute(s -> em.contains(detached[0])) + " -> detached");
Text
new:       managed=false id=null
Hibernate: select next value for author_seq
persisted: managed=true id=1
Hibernate: insert into author (name,id) values (?,?)
after commit: managed? false -> detached

A new object is transient: managed=false, no id. persist fetched an id from the sequence and made the object managed, but no insert ran yet. The insert appeared only when the transaction committed and the context flushed, which is the point of the next sections. After the commit the persistence context closed. The same Java object is now detached: it still carries its id and data, and nothing tracks it.

Dirty checking: updates without a save call

Inside a transaction, a managed entity is watched. Changing a field is enough.

java
tx.executeWithoutResult(s -> {
    Author loaded = em.find(Author.class, id);
    System.out.println("find twice, same instance? " + (loaded == em.find(Author.class, id)));
    loaded.name = "Ada Lovelace";                // no save, no persist, no merge
});
Text
Hibernate: select a1_0.id,a1_0.name from author a1_0 where a1_0.id=?
find twice, same instance? true
Hibernate: update author set name=? where id=?

Two facts show. The second find ran no SQL and returned the very same Java object: the first level cache guarantees one instance per row per context. And an update appeared at commit with no call that asked for it, because Hibernate compared the entity's state with the snapshot taken at load time and found a difference. This is why calling repository.save(entity) on a managed entity does nothing useful, and why people are surprised when an unintended change to a loaded entity, for example trimming a string in a getter, is written to the database.

Detached entities and merge

A detached object is not tracked, so changing it does nothing until it is attached again. merge copies its state onto a managed instance and returns that instance; it does not attach the object you passed.

java
detached[0].name = "Augusta Ada";
tx.executeWithoutResult(s -> {
    Author merged = em.merge(detached[0]);
    System.out.println("merge returns the managed copy: sameObject=" + (merged == detached[0])
            + " managed=" + em.contains(merged));
});
Text
Hibernate: select a1_0.id,a1_0.name,b1_0.author_id,b1_0.id,b1_0.title from author a1_0 left join book b1_0 on a1_0.id=b1_0.author_id where a1_0.id=?
merge returns the managed copy: sameObject=false managed=true
Hibernate: update author set name=? where id=?

merge first loaded the row, including the books association because it is cascaded, which explains the join in the first statement. It returned a different object (sameObject=false) that is managed, and the original stays detached. Code that calls em.merge(x) and keeps using x is a classic bug: later changes to x are lost. Always use the returned instance.

Removed

remove schedules a delete and changes the state at once, but the row disappears only at flush.

Text
removed:   managed=false
Hibernate: delete from author where id=?

Between remove and commit, the object is in the removed state, so contains reports false. Hibernate also loaded the author's books collection before the delete, because of the cascade, which is why a cascade on a large collection makes deletes expensive. Think about cascade as a statement about lifecycle: delete the parent, and its children must go too.

Exceptions as state hints

Many persistence errors are state errors in disguise. PersistentObjectException: detached entity passed to persist means persist received an object with an id that is not managed; use merge or load it first. TransientPropertyValueException means a managed entity points at one that was never persisted. LazyInitializationException means the context that would load a proxy is closed, so the object is detached. EntityExistsException and NonUniqueObjectException mean two instances for one row in one context. When one of these appears, ask in which state each object was at the time, and the fix usually names itself.

Practical rules that follow from the states

Five rules summarise how to work with the states. Open the persistence context at the service method, not at the controller, so each use case has one context and one transaction. Never pass managed entities to code that outlives the transaction; map them to DTOs inside it. Do not call save on a managed entity to make an update happen, because dirty checking already does it, and the call only adds noise that suggests the code works differently than it does. Use merge only for detached input, and use its return value. And keep transactions short, because the persistence context grows with every loaded entity and slows each flush, which is why long batch loops should call flush and clear every few hundred rows.

java
for (int i = 0; i < rows.size(); i++) {
    em.persist(rows.get(i));
    if (i % 500 == 499) { em.flush(); em.clear(); }   // keep the persistence context small
}

Where this does not apply

Stateless sessions (StatelessSession) skip the persistence context for bulk work and have no states. Reference: the Hibernate entity state section and the Jakarta Persistence specification.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.