2 Replies Latest reply on Dec 5, 2005 3:59 AM by Ian Hunter

    How to do self ref. entities in EJB3

    Ian Hunter Newbie

      I want to model a simple parent/child relation wher parent/child is in same table. (Code is below)

      I'm having difficulty when I want to delete the parent and leave the children with null parents.

      I *think* I simply setParent(null) on all children, setChildren(null) on parent (or use empty ArrayList), and them remove() the parent.

      This yields exceptions on the remove which I think indicate DB integrity issues.

      Anyhow. Is my approach OK with EJB3, or is there something I've missed.

      Can anybody point me at a working example?

      Many Thanks for any help
      Ian Hunter


      @Entity
      public class ManagedObject {
      
       @Id
       public String getId() {
       return dn;
       }
      
       public void setId(String dn) {
       this.dn = dn;
       }
      
       @OneToMany(fetch = FetchType.EAGER)
       public Collection<ManagedObject> getChildren() {
       return children;
       }
      
       public void setChildren(Collection<ManagedObject> children) {
       this.children = children;
       }
      
       @ManyToOne
       public ManagedObject getParent() {
       return parent;
       }
      
       public void setParent(ManagedObject parent) {
       this.parent = parent;
       }
      
       private Collection<ManagedObject> children;
       private ManagedObject parent;
       private String id;
      
      }
      


        • 1. Re: How to do self ref. entities in EJB3
          YCS WYW Newbie

          I think you should have to define the "JoinColumn" for the relations (to really setup the parent/childs in the same table) :

          @Entity
          public class ManagedObject {

          @Id
          @Column(name="ID")
          public String getId() {
          return dn;
          }

          public void setId(String dn) {
          this.dn = dn;
          }

          @OneToMany(fetch = FetchType.EAGER)
          @JoinColumn(name="PARENT")
          public Collection getChildren() {
          return children;
          }

          public void setChildren(Collection children) {
          this.children = children;
          }

          @ManyToOne
          @JoinColumn(name="PARENT")
          public ManagedObject getParent() {
          return parent;
          }

          public void setParent(ManagedObject parent) {
          this.parent = parent;
          }

          private Collection children;
          private ManagedObject parent;
          private String dn;

          }


          And then, you can directly delete the parent with "entityManager.remove(parent)"
          (without setting parent.setChildren(null) nor setParent(null) on all children).

          • 2. Re: How to do self ref. entities in EJB3
            Ian Hunter Newbie

            Thanks Mr/Ms. ycswyw - thats done the job.

            Ian