Hibernate: PersistentObjectException, detached entity passed to persist
org.hibernate.PersistentObjectException: detached entity passed to persistShort answer
persist() is for new objects. Hibernate raises this error when the object you pass already has an identity, because it was loaded earlier, or because you set its id yourself, or a cascade reaches such an object. Use merge (or Spring Data save), do not set generated ids by hand, and check where PERSIST cascades.
Fix it fast
1Find out which cause you have
Find the call that fails and print the id of the object you pass. A non-null id on an object you think is new points at the first cause. A null id on the parent means the cascade is the problem.
log.info("persisting id={} class={}", entity.getId(), entity.getClass());2Match what you see, then jump to its fix
What does the error look like?
org.hibernate.PersistentObjectException: detached entity passed to persistjakarta.persistence.EntityExistsException
Cause 1 of 2
persist() is called on an object that already has an id
1Check
The Jakarta Persistence API says that when an entity is detached, EntityExistsException may be thrown when persist is invoked, or at flush or commit time. An entity that has an id but is not in the current persistence context counts as detached.
grep -rn "\.persist(\|setId(" src/main/java2Fix
Use merge to bring existing data back into the context, and leave the id empty for a new object with a generated id. With Spring Data, call save(): it uses persist for a new entity (null id, or null version if there is a @Version attribute) and merge otherwise.
// existing row: merge returns the managed copy
Customer managed = em.merge(customer);
// new row: the id must be null
customer.setId(null);
em.persist(customer);3Verify
The save succeeds, and an update changes the row instead of failing.
SELECT id, name FROM customer WHERE id = 42;Confirmed by jakarta.ee
Cause 2 of 2
A cascade of PERSIST reaches an object that already exists
1Check
CascadeType.PERSIST (and ALL, which includes it) cascades the persist operation to the associated entity. If that associated entity is an existing, detached row, the cascaded persist fails the same way.
grep -rn "cascade" src/main/java2Fix
Remove PERSIST from the cascade on associations that point at existing rows, and cascade only from parent to children that you create together with the parent.
// before: @ManyToOne(cascade = CascadeType.ALL)
@ManyToOne
private Category category;3Verify
Save a parent that references an existing child.
repository.save(product);Confirmed by jakarta.ee
How do I stop it coming back?
- Use persist only for new objects with a null id, and merge (or Spring Data save) for the rest.
- Let the database generate ids; do not copy ids from client payloads into new entities.
- Cascade from a parent to children that it owns, not to shared reference data.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Databases
Hibernate cannot initialize a lazy collection or proxy in Spring Boot
could not initialize proxy - no Session
A lazy collection or proxy is loaded on first access, and that needs an open Hibernate session.
3 causes, each with a fixBack end
Go database/sql fails to scan a NULL column, and stores empty strings instead of NULL
unsupported Scan, storing driver.Value type <nil> into type *string
database/sql hands a NULL to Scan as nil, and a plain *string cannot hold it, so Scan returns an error.
2 causes, each with a fixBack end
Apache HttpClient 5 has no setSSLSocketFactory on HttpClients.custom()
HttpClients.custom().setSSLSocketFactory() method not found
In Apache HttpClient 5 the TLS setup no longer sits on the client builder.
2 causes, each with a fixBack end
A scanner flags jackson-databind: how to upgrade it in Gradle
jackson-databind vulnerability reported by a dependency scanner
Find where the old jackson-databind comes from, then raise it.
3 causes, each with a fixBack end
Spring Boot cannot bind spring.datasource.password with Jasypt ENC() values
Failed to bind properties under 'spring.datasource.password' to java.lang.String
The binding error means Jasypt could not turn the ENC(...) value back into plain text.
3 causes, each with a fixBack end
Knex runs out of connections and the query waits until it times out
Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?
Every query needs a free connection from Knex's pool.
3 causes, each with a fix