Quick revision
The short answer
merge(detached) looks up the entity with the same id in the persistence context, loading it from the database with a SELECT if it is not there yet, copies the detached object's state onto that managed instance, and returns the managed instance. The argument itself stays detached, so changes made to it after merge are ignored; only the returned object is tracked. Cascade MERGE applies the same process to associations, and newer Hibernate versions treat a detached entity whose row no longer exists as a stale-state error rather than inserting it, so check your version.
What to remember
In this answer, we saw that merge looks up the managed entity with the same id, loading it with a SELECT if needed, copies the detached object's state onto it, checks the version if there is one, and returns the managed instance. The argument stays detached, so changes made to it afterwards are lost; we must continue with the returned object, including the one Spring Data's save() returns. Cascade MERGE repeats the process for associations, and newer Hibernate versions report a detached entity whose row no longer exists as stale state instead of inserting it again.
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.
merge(detached) looks up the entity with the same id in the persistence context, loading it from the database with a SELECT if it is not there yet, copies the detached object's state onto that managed instance, and returns the managed instance. The argument itself stays detached, so changes made to it after merge are ignored; only the returned object is tracked. Cascade MERGE applies the same process to associations, and newer Hibernate versions treat a detached entity whose row no longer exists as a stale-state error rather than inserting it, so check your version.
Why this question is asked
merge is the most misunderstood method on EntityManager because its name suggests that the object we pass in joins the persistence context. It does not, and that one detail explains a whole class of bugs where changes are silently lost. Interviewers ask about merge internals to see whether we can reason about object identity in JPA, not just call save(). In this answer, we will recap detached entities, walk through what merge does step by step, reproduce the lost change, look at cascading, and finish with how merge treats rows that no longer exist.
1A Quick Recap of Detached Entities
A managed entity is one that a persistence context tracks; Hibernate compares it with its loaded state at flush and writes changes automatically. A detached entity was managed once, but its persistence context has closed, usually because the transaction ended. It still holds an id and data, but nothing tracks it.
merge exists to bring the state of such an object back into a persistence context. The important word is state: merge transfers data, not the object itself.
2What merge Does, Step by Step
When we call em.merge(detached), Hibernate first reads the id of the detached object and looks in the current persistence context for a managed entity with that id. If it finds one, it uses it. If not, it loads the entity from the database with a SELECT, which makes a fresh managed instance.
Next, it copies the detached object's state onto the managed instance, attribute by attribute: simple fields, and associations according to cascade settings. If the entity has a @Version attribute, Hibernate checks it here: if the detached version is older than the one in the database, it throws an optimistic locking exception instead of overwriting newer data.
Finally, merge returns the managed instance. That object is tracked, so its new state is written at flush as an ordinary dirty-checked UPDATE. The argument is left exactly as it was: still detached, still untracked.
7 messages in order. Play them, or step through them one at a time.
The argument stays detached; only the returned object is tracked.
3Reproducing the Lost Change
Here is the bug that follows directly from those steps. The developer calls merge, then keeps changing the object they already had.
| Argument (detached) | Returned instance | |
|---|---|---|
| Tracked by the persistence context | No | Yes |
| Changes written at flush | No | Yes |
| Same object as before merge | Yes | No (managed copy) |
em.contains(...) | false | true |
Notice that the first version does write an UPDATE, with the state the detached object had at the moment of merge. The later change to the argument never reaches the persistence context, so it is silently lost. The same happens with Spring Data: save() returns the merged instance for existing entities, and code that ignores the return value and keeps using its own object has exactly this bug.
4Cascade MERGE and Associations
By default, merge copies the entity's own attributes, and for associations it only copies the reference: the managed instance ends up pointing at the managed version of the associated entity, but the associated object's changed fields are not copied. With cascade = CascadeType.MERGE (or ALL) on the association, Hibernate runs the same process for the associated entities too: look up or load each one, copy its state, and link the managed copies.
This matters for object graphs edited outside a transaction, such as an order with its lines. With cascade MERGE on the lines, merging the order also merges each line, and new lines without an id are inserted. Each step is a lookup and possibly a SELECT, so merging a large graph can be expensive, and orphaned lines are only deleted if orphanRemoval is set.
5When the Row No Longer Exists
What should merge do if the detached object has an id, but its row has been deleted in the meantime? The older behaviour of Hibernate was to treat the object like a new one and insert a fresh row, sometimes with a new generated id. That can quietly resurrect data that someone deliberately deleted.
Newer Hibernate versions changed this: merging a detached entity with a generated id, or a version, whose row no longer exists is treated as stale state and raises an optimistic locking error rather than inserting. This change arrived in the Hibernate 6.6 line, as far as I recall, so check your version and its migration guide before relying on either behaviour. Either way, the safer design is a @Version attribute, so concurrent changes and deletions are detected explicitly.
6Follow-up questions
Why does merge run a SELECT even when we only want an UPDATE?
Because Hibernate needs a managed instance to copy the state onto, and to check the version, and it can only get one by finding it in the context or loading it. That SELECT is the cost of merge. If we only want to change one column for a known id, a bulk JPQL UPDATE or loading and changing the entity inside one transaction is cheaper and clearer.
What does merge do with a new entity that has no id?
It treats it as new: it creates a managed copy, schedules an INSERT, and returns the copy. The argument still stays new and untracked, so its generated id is set on the returned instance, not on the argument. Code that reads the id from the argument after merge gets null, which is another reason persist is the better operation for new entities.
Is there a Hibernate alternative to merge that reattaches the original object?
Hibernate's older Session.update() and saveOrUpdate() reattached the object itself, but they were deprecated in Hibernate 6 and removed in Hibernate 7, so new code should use merge and work with its return value. Check your version if you maintain old code that still calls them.
7Conclusion
In this answer, we saw that merge looks up the managed entity with the same id, loading it with a SELECT if needed, copies the detached object's state onto it, checks the version if there is one, and returns the managed instance. The argument stays detached, so changes made to it afterwards are lost; we must continue with the returned object, including the one Spring Data's save() returns. Cascade MERGE repeats the process for associations, and newer Hibernate versions report a detached entity whose row no longer exists as stale state instead of inserting it again.
Open with
merge does not attach the object I pass in. It reads the id, looks for a managed entity with that id in the current persistence context, and if it is not there, loads it from the database with a SELECT.
Then, if they want more
Then it copies the state of my detached object onto that managed instance, checking the version first if the entity has a @Version field, and it returns the managed instance. My original object is untouched and still detached.
So if I call merge and then keep calling setters on the argument, those changes never reach the persistence context and are silently lost; the UPDATE at commit contains the state as it was at the moment of merge.
The fix is to always use the returned instance, and the same goes for Spring Data's save, which calls merge for existing entities. For associations, merge only links references by default; with cascade MERGE it repeats the same lookup and copy for each associated entity, and inserts new children, which can mean several SELECTs for a large graph.
One version detail: older Hibernate would insert a new row if the detached entity's row had been deleted meanwhile; newer versions, from the 6.6 line I believe, treat that as stale state and throw an optimistic lock error. I would check the version and use @Version to be explicit.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Hibernate 6, Hibernate 7
- 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 "Explain what entityManager.merge(detached) actually does, and why changes made to the...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/3d99574278/