views:

51

answers:

1

Hi,

I have one-to-many relationship between parent and child Java objects. The parent object uses java.util.List that stores multiple child objects. The problem I am experiencing is when updating the parent object after I have added one or more child object(s) to the List in the parent. I am using the saveOrUpdate method to save or update the parent. It works fine if I am saving a new instance of the parent, but after saving it, I try to add child object(s) into the parent List and then attempt to call saveOrUpdate on the parent object, but no entries of child object(s) get persisted into the database. I just would like some pointers. Note: I am not using annotations.
A snippet of the Parent.hbm.xml, that defines the one-to-many unidirectional relationship:

  <list name="children" cascade="all">
     <key column="parent_id"/>
     <index column="idx"/>
     <one-to-many class="Child"/>
  </list>
+1  A: 

I just tried to reproduce this example and it worked OK for me.

Here are my mappings:

<hibernate-mapping package="com.example.domain">
    <class name="com.example.domain.Parent" table="PARENT">

        <id name="id" column="parent_id" access="field">
            <generator class="increment" />
        </id>
        <property name="name" column="parent_name" access="field" />

        <list name="children" access="field" cascade="all">
            <key column="parent_id" not-null="true" />
            <index column="idx" />
            <one-to-many class="Child" />
        </list>
    </class>
</hibernate-mapping>

<hibernate-mapping package="com.example.domain">
    <class name="com.example.domain.Child" table="CHILD">
        <id name="id" column="child_id" access="field">
            <generator class="increment" />
        </id>
        <property name="name" column="child_name" access="field" />
    </class>
</hibernate-mapping>

I added not-null="true" to the parent mapping.

Did you try to set show_sql in your hibernate config to see generated SQL?

Roman
Thanks Roman. I have tried as you suggested. But, Im getting an exception:"org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: Parent.children, no session or session was closed". JUnit test fail on the parent.getChildren after loading the parent from the database.
walters
Yes, this happens with detached entities. Depending on the requirements (for example whether children must be loaded all the time) you can load them eagerly (to do this you can set lazy="false" on the list). You can read a bit more on the Hibernate website: http://docs.jboss.org/hibernate/core/3.5/reference/en/html/performance.html#performance-fetching-lazy . Also, consider "Open Session In View" pattern.
Roman
Also, this SO thread has more information on this problem: http://stackoverflow.com/questions/345705/hibernate-lazyinitializationexception-could-not-initialize-proxy
Roman