开发者

Hibernate One To Many Unidirectional Mapping List

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="开发者_如何学JAVAparent_id"/>
     <index column="idx"/>
     <one-to-many class="Child"/>
  </list>


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜