title: Hibernate Save strange behaviour
body: <p>I have a user object that has a one-to-many relationship with String types. I believe they are simple mappings. The types table hold the associated user_id and variable type names, with a primary key 'id' that is basically a counter.</p>
  
  <pre><code>&lt;class name="Users" table="users"&gt;
      &lt;id column="id" name="id" /&gt;
      ...
      &lt;set name="types" table="types" cascade="save-update"&gt;
          &lt;key column="id" /&gt;
          &lt;one-to-many class="Types" /&gt;
      &lt;/set&gt;
  &lt;/class&gt;
  
  &lt;class name="Types" table="types"&gt;
      &lt;id column="id" name="id" /&gt;
      &lt;property column="user_id" name="user_id" type="integer" /&gt;
      &lt;property column="type" name="type" type="string" /&gt;
  &lt;/class&gt;
  </code></pre>
  
  <p>This is the java I used for adding to the database:</p>
  
  <pre><code>User u = new User();
  u.setId(user_id);
  ...
  Collection&lt;Types&gt; t = new HashSet&lt;Types&gt;();
  t.add(new Type(auto_incremented_id, user_id, type_name));
  u.setTypes(t);
  
  getHibernateTemplate().saveOrUpdate(u);
  </code></pre>
  
  <p>When I run it, it gives this error:</p>
  
  <pre><code>61468 [http-8080-3] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1062, SQLState: 23000
  61468 [http-8080-3] ERROR org.hibernate.util.JDBCExceptionReporter - Duplicate entry '6' for key 'PRIMARY'
  61468 [http-8080-3] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
  org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
  </code></pre>
  
  <p>When I check the sql, it shows:</p>
  
  <pre><code>Hibernate: insert into users (name, id) values (?, ?)
  Hibernate: insert into types (user_id, type, id) values (?, ?, ?)
  Hibernate: update types set id=? where id=?
  </code></pre>
  
  <ul>
  <li>Why does Hibernate try to update the types' id?</li>
  </ul>
  
  <p>The error says: Duplicate entry '6' for key 'PRIMARY', but there really isn't? I made sure the ids are incremented each time. And the users and types are added into the database correctly.</p>
  
  <p>I logged the information going in, and the types added has an id of 7 and a user id of 6. Could it be that Hibernate takes the user_id of 6 and tried to update types and set id=6 where id=7? Therefore the duplicate primary key error?</p>
  
  <p>But why would it do something so strange? Is there a way to stop it from updating?</p>
  
  <ul>
  <li>Should I set the id manually? If not, then how should I add the types? It gives other errors when I add a type object that only has a type string in it and no ids.</li>
  </ul>
  
  <p>Thanks guys. Been mulling over it for days...</p>