title: Hibernate, parent/child confusion
body: <p>I have a simple object relation, I wish to persist with hibernate.</p>
  
  <p>Basically, its a Parent which contains a collection of Children. All I wish to do, is load the parent if it exists, otherwise create it, add elements to it and save it.</p>
  
  <p>This is being done in a GWT enviroment, so I pass a ChildDTO to this method, which is basically just a non-persistant version of the Child class (which is incompatible with gwts RPC serialization).</p>
  
  <pre><code>public Integer testHibernate(Integer parentId, ChildDTO[] test) {
      Session session = HibernateUtil.getSessionFactory().getCurrentSession();
      session.beginTransaction();
  
      Parent model;
      if(parentId == null) {
          // if the parentId is null, create new instance 
          model = new Parent ); 
      }
      else {
          model = (Parent) hib.load(Parent.class, dto.getId());
      }
  
      model.setName("dummy name");
  
      for(int i = 0; i &lt; test.length) {
          model.addChild(new Child(test[i].getId(), test[i].getName()));
      }
  
      hib.save(model);        
      hib.getTransaction().commit();
  
      return model.getId();
  }
  </code></pre>
  
  <p>Right, this works fine for creating new Parents, without children. It also works fine if i am just adding one child to an existing parent. However, if i add more than one child, i get a "could not insert" error from hibernate.</p>
  
  <p>Also, if I try adding just one child, to a already existing parent, which already have one child added. I get a "a different object with the same identifier value was already associated with the session" error.</p>
  
  <p>Additional question. When inserting just one child, on a empty parent, hibernate does the following:</p>
  
  <pre><code>Hibernate: insert into Child(ChildId, ChildName) values (default, ?)
  Hibernate: update Parent set ChildId=? where ChildId=? 
  </code></pre>
  
  <p>Whats with the update? :S</p>