Pergunta

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>
Foi útil?

Solução

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?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top