2

I'm having issues with a parent-child relationship here. When I persist from the collection side (child side) I get 2 new children instead of one.

Here is are the hibernate mappings:

    <set name="children" inverse="true"
        cascade="all,delete-orphan" lazy="true"
        order-by="CHILD_ID desc">
        <key column="PARENT_ID" />
        <one-to-many class="com.mycompany.Child" />
    </set>
    <many-to-one name="parent" class="com.mycompany.Parent" not-null="true">
        <column name="PARENT_ID" />
    </many-to-one>

Here is the java code used to add the child into the bidirectional relationship:

// Persist logic...
Parent p = myParentService.findById(1);
Child c = new Child();
p.addChild(c);
myChildService.persist(child);

// Inside the parent class...
public void addChild(Child child)
{
    if (this.children == null)
        this.children = new LinkedHashSet<Child>();

    this.children.add(child);
    child.setParent(this);
}

If I remove the "this.children.add(child);" part everything works as expected. This is confusing because the Hibernate documentaion here says that bidirectional relationships are supposed to work this way. What am I missing?

4

1 回答 1

2

您在父集合上打开了级联持久化,因此无需在子实体上显式调用持久化。如果父级处于托管状态,则新的子级将在下一次事务提交/同步时持久化。您链接的示例文档中未打开级联。

于 2010-07-30T18:41:54.793 回答