6 Replies Latest reply on Oct 17, 2008 12:58 AM by Mark Thias

    Problem with composite Primary key which is also a foreign k

    Imran Pariyani Newbie


      I have a entity like:

      public class Parent implements Serializable {

      @OneToMany(cascade =CascadeType.ALL, mappedBy = "site", fetch=FetchType.EAGER)
      @OrderBy("position ASC")
      @Sort(type = SortType.NATURAL)
      private SortedSet childs;

      // method for adding the child object :
      public void addChild(Child child) {
      this.childs=new TreeSet();

      and the child class as follows:

      @Table(name = "child")
      public class Child implements Serializable, Comparable {
      private int parentId;

      private Language language;

      @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
      @JoinColumn(name = "parent_id",nullable = false,insertable = false, updatable = false, referencedColumnName = "id", columnDefinition = "parent_id INT NOT NULL")
      private Parent parent;

      And the primary key class as follows :

      public final class ChildPK implements Serializable {
      @Column(name = "parent_id",insertable = false, updatable = false, nullable = false)
      private int parentId;

      private Language language;

      public boolean equals(Object other) {.....}


      now the problem is if i am inserting a new parent with a new child .. it inserts the parent and then tries to insert the child with the parentId(foreign key) as 0 ...

      in other case where there is no composite key it inserts the parent and then gets the autogenerated parent id and assigns it the child and then inserts the child .. why dosent that happen with the child with composite key.

      What am i doing worng?

      Any help would be appreciated