0 Replies Latest reply on Oct 16, 2008 5:38 AM by thhal

    Parent/Child, merge, and assignment of generated ID

    thhal

      I'm using JBoss 4.2.3 with Hibernate and I have the following scenario.

      Two entities, let's call them 'Parent' and 'Child'. A Parent has many Children. The relationship in Parent is declared using javax.persistence annotation like this:

      @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
      public List getChildren() {
      return m_children;
      }

      Both Parent and Child has a primary key that is auto generated. We use the annotations:
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)

      Now I have a Parent instance and I want to add a child to it. So I do like this (the EntityManager em is obtained with @PersistenceContext annotation):
      Child child = new Child(parent);
      parent.getChildrent().add(child);
      em.merge(parent);

      This works. I.e. the child is correctly inserted into the database. The only problem is that after the commit, the generated ID of the child is still null. I can remedy this by doing:
      Child child = new Child(parent);
      em.persist(child);
      parent.getChildrent().add(child);

      This also works and now the ID is assigned to the child directly by the call to persist. My question is, why is it not assigned in my first example?

      I can see the normal "select nextval ('hibernate_sequence')" when I step over the merge call in the debugger so the child ID is obviously obtained at that very moment. The actua insert however, does not happen until later. Where is the ID stored in the meantime?

      Regards,
      Thomas Hallgren