Hibernate,一对多,未插入父项的子项

时间:2012-10-17 11:12:59

标签: java hibernate

我有一个双向的一对多关系,即一个父母可以有很多孩子,一个孩子必须有一个父母,很多孩子可以有同一个父母。

请参阅以下hibernate xml配置。这适用于加载对象。通过其id成功选择父对象将返回包含一组子对象(如果有)的父对象。

但是,当我创建一个新的父项时,添加一些子项然后请求hibernate创建父项,子项不会随之保存。我原本以为hibernate会为我处理这个问题吗?

我怀疑我的问题是因为父母有一个db托管序列作为id,所以孩子们在插入父代之前不能拥有父代的id。但是,对于hibernate来说,这应该不是很难处理吗?

Parent.hbm.xml;

<hibernate-mapping default-cascade="none">
    <class name="com.mydomain.ParentImpl" table="PARENT" dynamic-insert="false" dynamic-update="false">
        <id name="id" type="java.lang.Long" unsaved-value="null">
            <column name="ID" sql-type="BIGINT"/>
            <generator class="sequence">
                <param name="sequence">PARENT_SEQ</param>
            </generator>
        </id>
        ....
        lots of other properties
        ...
        <set name="children" lazy="true" fetch="select" inverse="true">
            <key foreign-key="parent_child_fkc">
                <column name="PARENT_FK" sql-type="BIGINT"/>
            </key>
            <one-to-many class="com.mydomain.ChildImpl" not-found="exception"/>
        </set>
   </class>
</hibernate-mapping>

Child.hbm.xml;

<hibernate-mapping default-cascade="none">
    <class name="com.mydomain.ChildImpl" table="CHILD" dynamic-insert="false" dynamic-update="false">
        <id name="id" type="java.lang.Integer" unsaved-value="null">
            <column name="ID" sql-type="INTEGER"/>
            <generator class="sequence">
                <param name="sequence">child_seq</param>
            </generator>
        </id>
        <many-to-one name="parent" class="com.mydomain.ParentImpl" foreign-key="parent_child_fkc" not-null="true" lazy="proxy" fetch="select">
            <column name="PARENT_FK" not-null="true" sql-type="BIGINT"/>
        </many-to-one>
        ...
        lots of other properties
        ...
    </class>
</hibernate-mapping>

假设Parent类有方法;

public void addChild(Child child){
    if(children == null) {
        children = new HashSet<Child>();
    }
    children.add(child);
    child.setParent(this);
}

然后在某处的代码中;

Parent parent = new Parent();
parent.addChild(new Child());
parent.addChild(new Child());
getHibernateTemplate().save(parent);

结果是Parent保存到PARENT表,CHILD表保持为空。

1 个答案:

答案 0 :(得分:0)

您需要使用映射和级联来保存子对象。

<set name="children" inverse="true" cascade="all-delete-orphan">
<key column="parent_id"/>
<one-to-many class="Child"/>

见这里:

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/example-parentchild.html#example-parentchild-update

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/collections.html