0 Replies Latest reply on Oct 5, 2005 9:25 PM by Zihong Lu

    problem in updating children in OneToMany

    Zihong Lu Newbie

      I have a problem in the updating children in OneToMany relationship.

      The parent class P and child class C are annotated as the following:


      @Entity(access=AccessType.PROPERTY)
      public class Parent
      {
      private int id;
      private int version;
      private Set children = new HashSet();

      @OneToMany(mappedBy="Child", fetch=FetchType.LAZY,
      cascade={CascadeType.MERGE, CascadeType.REMOVE})
      public Set getChildren() {return children;}

      public addChild(Child c)
      {
      children.add(c);
      c.setParent(this);
      c.setParentId(this.getId());
      }

      public void removeChild(Child c) {children.remove(c);}
      ...
      }


      @Entity(access=AccessType.PROPERTY)
      public class Child
      {
      private int id;
      private int version;
      private int parentId;
      private Parent p;

      @ManyToOne
      @JoinColumn(name="parentId", insertable=false, updatable=false)
      public JDevice getParent() {return this.p; }
      public addParent(Parent p) {this.p = p; }
      ...
      }


      When users obtain an object p, remove one child c1 from p's children collection, by calling

      p.removeChild(c1);
      entityManager.merge(p);


      Should the entity manaager automatically do a remove of the c1, ie, support persistance by reachability?

      Instead, I found out that the database still has this c1 object record, and the server log did not have a trace of removing this object.

      Is this a bug?


      On a relevent issue: if I don't setup the CascadeType to ALL, I have to map the parentId as a separated member property, and need to set the JoinColumn annotation to updatable=false, insertable=false. This has an ugly ramification: in the parent side, when I do addChid(), I have to specifically set the parentId into the child, as shown in the code above. Is this the right way to do it? If I don't this, I always get foerign key violation exception.



      -Zihong