Is it possible to move an entity from one collection to another?
I have two top level entities A and B which both have one-to-many
references to another entity C, which happens to have its own network
of stuff below it.
Cascade deletes are working fine - if I delete C, it and everything
below it goes away. Also, if I delete A or B, then it and its
children also go away. So far so good, and I want to keep this
cascading behavior.
Now the interesting part.
I want to take C, remove it from A's one-to-many collection and add it
to B's one-to-many collection, preserving the object network under c.
a.getChildren().remove( c );
c.setParent(null);
b.getChildren().add(c);
c.setParent( b );
I get errors like "Found two representations of same collection" the
moment I do the add().
I'd think this would be a trivial reassignment of some foreign keys,
but there seems to be more to the story. Anyone know what it is?
Does Hibernate assume remove() is a delete? The object c is not being
orphaned.
Thanks,
-Walt Stoneburner, wls@wwco.com
wls - 15 Nov 2007 21:09 GMT
> Is it possible to move an entity from one collection to another?
> ...
> I get errors like "Found two representations of same collection" the
> moment I do the add().
For those who stumble upon this post in the future, it turns out that
the collections had the CASCADE_DELETE option set.
When cascade-delete is used in conjunction with remove(), it appears
that the object actually stays behind in the collection in a state
that is marked for deletion [even though the object part of the ORM
stays around]; when the object is re-added to another collection,
Hibernate thinks there is a duplicate.
The solution is to remove cascade-delete and handle the deletion of
associations manually.
See http://forum.hibernate.org/viewtopic.php?t=981282 for the answer
to this question, along with a pretty graphical picture of the
problem.
-wls