0 Replies Latest reply on May 1, 2008 10:21 AM by Justin Miller

    JPA OneToMany bidirectional -- Entity deletion

    Justin Miller Newbie

      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})
       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:


      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();
       for(A child : children) {

      And in the second transaction:

      instanceOfA = entityManager.find(A.class, instanceOfA.getId());

      This works, but feels very clunky.

      What is the proper way to do this?