[jboss-user] [Persistence, JBoss/CMP, Hibernate, Database] - Parent/Child, merge, and assignment of generated ID

thhal do-not-reply at jboss.com
Thu Oct 16 05:38:56 EDT 2008


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


View the original post : http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4182595#4182595

Reply to the post : http://www.jboss.com/index.html?module=bb&op=posting&mode=reply&p=4182595



More information about the jboss-user mailing list