2 Replies Latest reply on Apr 8, 2006 7:13 PM by oliverchua

    ManyToOne - Problems managing relationships

    colin_e

      Dear All,

      I have a simple Parent-Child relationship as illustrated by the following entities:

      @Entity(access = AccessType.FIELD)
      class ParentBean implements Serializable
      {
       @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
       private Collection<ChildBean> children;
      
       Collection<ChildBean> getChildren()
       {
       return children;
       }
      
       void removeChild(ChildBean child)
       {
       children.remove(child);
       }
      
       addChild(ChildBean child)
       {
       children.add(child);
       child.setParent(this);
       }
      }


      @Entity(access = AccessType.FIELD)
      class ChildBean implements Serializable
      {
       @ManyToOne
       private ParentBean parent = null;
      
       void setParent(ParentBean parent)
       {
       // if this child is already associated with a parent, remove
       // the old association.
       if (this.parent!=null)
       {
       this.parent.removeChild(this);
       }
       this.parent = parent;
       }
      }


      i.e. The Child entity owns the relationship. The relationship is formed by calling the addChild method on the Parent. If we attempt to add a Child to a Parent with Child that has already been added to a Parent, in order to avoid vilating the one-ness of this relationship, we call removeChild on teh previous Parent after adding to the new one.

      Or at least that is what I want to happen. However if I do the following:

      //construct a parent object and add a child to it
      ParentBean parentOne = new ParentBean();
      ChildBean childOne = new ChildBean();
      parentOne.addChild(childOne);
      manager.merge(parentOne);
      
      //construct a new parent and add the same child
      ParentBean parentTwo = new ParentBean();
      parentTwo.addChild(childOne);
      manager.merge(parentTwo);


      I find that both parentOne and parentTwo are associated with different Child entities, looking in the database it would appear that the Child has been cloned and each Parent has a copy.

      Furthermore, if I change the EntityManager operations from merge to persist, I get a TransientObjectException thrown.

      Can anyone tell me what I am doing wrong. As I said, all I want is that if I add a Child to a parent, that any previous Parent associations of that Child are removed.

      BTW. I am using JBoss 4.0.3 SP1

      Regards,
      Colin E.