• Post Reply Bookmark Topic Watch Topic
  • New Topic

Issues with Cacade.Merge  RSS feed

Matt Pennington
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm hoping someone here can help with my understanding on this problem I'm having using Cascade.merge in Hibernate.

I've got a parent entity which has a collection of child entities. They are all detached and I want to reattach them all to the new persistence context so that I can use them accordingly.

I've marked the OneToMany relationship as Cascade.All and performed a merge on the parent entity. However all my references to the child entities in the collection remain detached - I get a "detached entity" error when I try to do something that requires them to be attached: e.g. removing them.

I *think* this is because the merge operation doesn't reattach your entity to the persistence context, rather it makes the data in the database consistent with the data in the entity. To make your variable point to the persisent entity you have to set it equal to the object returned from the merge operation. e.g. foo = EntityManager.merge(foo);

That would logically imply that the references to the child data in the collection held by the parent have their data synchronized with the database, but the variables are not updated to point to the persistent entities, so any attempt to use them as if they were attached throws an error.

Obviously I don't want it to work like that, so in the vain hope that I have it wrong, I've been scouring the documentation and forums for any help/insight/confirmation on this issue, but I can't find anything of any use. If anyone can point me at the rough area in the Hibernate/JPA documentation that indicates if my understanding is or isn't correct it would be appreciated.

In terms of solutions, I could walk the object graph individually reattaching and resetting any reference. That seems... laborious and hence probably the "wrong" thing to do. The only other alternative I can see is to rewrite the rest of my code so that it no longer automatically assumes that it is working with persistent objects. Obviously I'd prefer to know if my understanding of merge is right before I set out doing that.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!