Quick revision
The short answer
After the transaction that loaded it ends, o is a detached entity: it has an id but no persistence context tracks it. persist only accepts new entities, so a detached object with an id is rejected with 'detached entity passed to persist'. We should either call merge to apply its state to a managed copy, or, better, load and change the entity inside one transaction; Spring Data's save() already calls merge for entities it does not consider new.
What to remember
In this answer, we saw that o became detached when the transaction that loaded it ended, because Spring binds the persistence context to the transaction. persist only accepts new entities, so a detached entity with an assigned id is rejected with 'detached entity passed to persist'. The best fix is to load and change the entity inside one transaction so dirty checking saves it; when the state really comes from outside, merge applies it to a managed copy, which Spring Data's save() also does for entities it does not consider new.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
After the transaction that loaded it ends, o is a detached entity: it has an id but no persistence context tracks it. persist only accepts new entities, so a detached object with an id is rejected with 'detached entity passed to persist'. We should either call merge to apply its state to a managed copy, or, better, load and change the entity inside one transaction; Spring Data's save() already calls merge for entities it does not consider new.
Why this question is asked
This error appears in almost every team's first months with JPA, usually when a service loads something, passes it around, and later tries to save it. The message is precise, but only if we know what detached and persist mean. Interviewers ask it because the answer shows whether we understand entity states and the difference between persist and merge. In this answer, we will reproduce the error, explain why o is detached, see why persist refuses it, and then look at the right fixes, including what Spring Data's save() does.
1Reproducing the Error
Here is the code from the question, with the transaction boundary made explicit. In a typical Spring application, the repository call runs in its own short transaction, so the entity outlives it.
Notice that nothing is wrong with the order itself. The problem is which operation we chose for an object in this state.
2Why o Is Detached
An entity is managed only while the persistence context that loaded it is open. In Spring, the persistence context is normally bound to the transaction. findById() on a Spring Data repository is transactional by itself, so it opens a transaction, loads the order, returns it, and commits. When that transaction ends, its persistence context closes, and every entity it loaded becomes detached.
A detached entity still has its id and all its data. But nobody tracks it any more: changing it does nothing, and lazy associations can no longer load.
3Why persist Rejects a Detached Entity
persist has one job: make a new entity managed and schedule an INSERT for it. When we call it, Hibernate checks what kind of object it received. If the object has an id that Hibernate considers already assigned, typically a generated id that is not null, and it is not in the current persistence context, Hibernate concludes the object represents an existing row it is not tracking, in other words a detached entity. Inserting it again would create a duplicate or fail on the primary key, so Hibernate refuses with a clear error instead of guessing what we meant.
So the message is really saying: this object already exists in the database; use the operation for existing objects.
- Is it already managed in this context?YesNothing to do (already tracked)NoContinue
- Does it have an assigned generated id?YesDetached: PersistentObjectExceptionNoNew: schedule INSERT, now managed
2 steps in order. Play them, or step through them one at a time.
persist is only for new entities.
4Fix 1: Load and Change Inside One Transaction
The cleanest fix is to avoid detached entities in the first place. If the code loads the order and changes it in one transactional method, the entity stays managed throughout, and dirty checking writes the change at commit without any save call.
This is also the safest version under concurrency, because the change is applied to the state just loaded, and a @Version field on Order turns lost updates into an optimistic locking error.
5Fix 2: merge the Detached Entity
When the detached object comes from elsewhere, for example it was loaded in one request and modified in another, merge is the right operation. It finds or loads the managed instance with the same id, copies the detached object's state onto it, and returns the managed instance.
There is a catch: merge copies every attribute of the detached object, including stale values another user may have changed in the meantime. With a @Version field, Hibernate compares versions and throws an optimistic locking exception instead of silently overwriting. Without one, the last writer wins.
6What Spring Data's save() Does
Most Spring code calls orderRepository.save(o) rather than the EntityManager directly. SimpleJpaRepository.save() asks whether the entity is new. By default, an entity is new if its id is null, or, when it has a non-primitive @Version attribute, if the version is null; an entity can also decide for itself by implementing Persistable. For new entities, save() calls persist; for the others, it calls merge.
So replacing entityManager.persist(o) with orderRepository.save(o) also fixes the error, because save() chooses merge. We should still prefer Fix 1 where we can, and always use the object save() returns.
7Follow-up questions
Why does the same error appear when saving a new entity with a manually set id?
With a generated id, Hibernate treats a non-null id as a sign the entity already exists. If code sets the id by hand on a new object and calls persist, Hibernate sees an assigned generated id and treats the object as detached. Either let the id be generated, or, for application-assigned ids, remove @GeneratedValue so Hibernate expects them, and use Persistable with Spring Data so save() knows the entity is new.
Can cascading cause this error even when the parent is new?
Yes. If a new Order has CascadeType.PERSIST to a Customer that was loaded in an earlier transaction, persisting the order cascades persist to the detached customer and fails with the same message. The fix is to attach the customer in the current transaction, for example with getReferenceById(customerId), instead of using the detached instance.
Is calling merge everywhere a safe default?
No. merge always runs a SELECT if the entity is not already loaded, copies all fields including stale ones, and returns a new object that callers often ignore. It is the right tool for genuinely detached state, but for ordinary updates, loading and changing in one transaction is cheaper and clearer.
8Conclusion
In this answer, we saw that o became detached when the transaction that loaded it ended, because Spring binds the persistence context to the transaction. persist only accepts new entities, so a detached entity with an assigned id is rejected with 'detached entity passed to persist'. The best fix is to load and change the entity inside one transaction so dirty checking saves it; when the state really comes from outside, merge applies it to a managed copy, which Spring Data's save() also does for entities it does not consider new.
Open with
The order is detached. findById runs in its own transaction, and in Spring the persistence context lives as long as the transaction, so when findById returns, the context closes and o is no longer tracked.
Then, if they want more
It still has its id and data, but changes to it go nowhere. persist is only for new entities: it schedules an insert and makes the object managed.
When Hibernate sees an object with an assigned generated id that its current context does not know, it concludes this is an existing row it is not tracking, and refuses with detached entity passed to persist instead of inserting a duplicate.
The best fix is to do the load and the change in one @Transactional method, so the entity stays managed and dirty checking writes the update at commit, with no save call at all.
If the object really comes from another request, I would call merge, which loads the managed copy by id, copies the detached state onto it, and returns the managed instance, and I would keep working with that return value. A @Version field protects against overwriting someone else's change.
Spring Data's save would also work here, because for an entity with a non-null id it treats it as not new and calls merge.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "This code throws 'detached entity passed to persist':": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/5591fa5390/