views:

47

answers:

1

Hello everyone. 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?

+1  A: 

You turned on cascade persist on the parent's collection, so there is no need to call persist explicitly on the child entity. If the parent is in the managed state, the new child will be persisted the next time a transaction commits/there is a synchronization. Cascade is not turned on in the example documentation that you linked.

Affe
Are you saying that the cascade style is causing a duplicate child entry?
@caleb Enabling cascading shouldn't cause duplicates entries.
Pascal Thivent