title: How do I map a many-to-one association in Hibernate where the child has a composite key and a part of that is the primary key in the parent?
body: <p>I have a (legacy) table structure that looks a little bit like this:</p>
  
  <pre><code>table parent (
    parentid int (PK)
    ...
  )
  
  table child (
    parentid int (PK)
    childid int (PK)
    ...
  )
  </code></pre>
  
  <p>That is, part of the primary key of child is the primary key for parent. I have tried to map this (we use xml-based Hibernate) like this:</p>
  
  <pre><code>&lt;hibernate-mapping&gt;
  &lt;class name="com.example.MyParent" table="parent"&gt;
  
      &lt;id name="parentid" column="parentid" unsaved-value="0" &gt;
          &lt;generator class="identity"/&gt;
      &lt;/id&gt;
  
      &lt;set name="children" cascade="all"&gt;
          &lt;key&gt;
              &lt;column name="parentid"/&gt;
          &lt;/key&gt;
          &lt;one-to-many class="com.example.MyChild" /&gt;
      &lt;/set&gt;
  ...
  &lt;/class&gt;
  
  &lt;class name="com.example.MyChild" table="child"&gt;
      &lt;composite-id name="id" class="com.example.MyChildId"&gt;
          &lt;key-property name="parentid" column="parentid" /&gt;
          &lt;key-property name="childid" column="childid" /&gt;
      &lt;/composite-id&gt;
      ...
  &lt;/class&gt;
  </code></pre>
  
  <p></p>
  
  <p>Java class:</p>
  
  <pre><code>public void updateParent(MyParent param) {
      ht.saveOrUpdate(param);
  
  }
  </code></pre>
  
  <p>UPDATE:
  I had used the wrong relation type (updated), but now I have another problem: It seems that when creating the child rows in the table, the parentid is null. Since parentid is part of the composite key, they insert fails.</p>
  
  <p>From the log: </p>
  
  <pre><code>DEBUG SQL - insert into Child(PARENTID, CHILDID) values (?, ?)
  TRACE IntegerType - binding null to parameter: 1
  TRACE IntegerType - binding '5678' to parameter: 2
  WARN  JDBCExceptionReporter - SQL Error: -10, SQLState: 23502
  ERROR JDBCExceptionReporter - integrity constraint violation: NOT NULL check constraint;     SYS_CT_10028 table: Child
  </code></pre>