I am having trouble deleting an entity part of a part-whole hierarchy and mapped as a
OneToMany bidirectional relationship. For example:
...
| public class A {
| @OneToMany(mappedBy="parent", cascade={CascadeType.MERGE,
CascadeType.PERSIST})
| private Collection<A> children;
|
| @ManyToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST})
| @JoinColumn(name="PARENT_ID")
| private A parent;
| ...
| }
|
Instances of 'A' can, but do not HAVE to participate in this relationship.
Therefore, a cascade on remove is not appropriate, because for any given instance of
'A', a parent and/or any of the children can exist independent of that instance.
So basically I want to remove an instance of 'A', and at the same time have
it's child relationships updated -- basically pointing to a null parent.
What's the proper way to do this?
The first and most obvious way to me is:
| entityManager.remove(instanceOfA);
|
But that results in the cryptic error: "deleted entity passed to persist".
The only way I've gotten this to work so far is to use two transactions. In the first,
I simply break the relationships and merge the objects:
Collection<A> children = instanceOfA.getChildren();
| instanceOfA.setChildren(null);
|
| for(A child : children) {
| child.setParent(null);
| entityManager.merge(child);
| }
|
| entityManager.merge(instanceOfA);
|
And in the second transaction:
instanceOfA = entityManager.find(A.class, instanceOfA.getId());
| entityManager.remove(instanceOfA);
|
This works, but feels very clunky.
What is the proper way to do this?
Thanks,
Justin
View the original post :
http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4148113#...
Reply to the post :
http://www.jboss.com/index.html?module=bb&op=posting&mode=reply&a...