views:

576

answers:

1

Hi, any help you can give is very gratefully accepted. I've been looking at this problem over and over and cannot seem to find the solution. Its probably staring in me in the face :(

I have the following class with a list of parents and children to be persisted in a Hierarchy table.

class Item  
{  
    public virtual int Id {get;set;}  
    public virtual List`<Item`> Parents {get;set;}  
    public virtual List`<Item`> Children {get;set;}  
}

In the hibernate settings, I have:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
  assembly="Pl.Components" namespace="Pl.Components"`>  
    <class name="Pl.Components.Item, Pl.Components" table="Item">  
        <id name="Id" type="Int32"  column="Id" >  
            <generator class="identity" />  
        </id>  
        <bag name="Parents" lazy="true" table="Hierarchy" cascade="save-update">  
            <key column="ChildId"/>  
            <many-to-many class="Item" column="ParentId" />  
        </bag>  
        <bag name="Children" lazy="true" table="Hierarchy" cascade="delete">  
            <key column="ParentId"/>  
            <many-to-many class="Item" column="ChildId"/>  
        </bag`>  
    </class>  
</hibernate-mapping>

This is causing duplicate keys in the Hierarchy table as the key pairs are inserted for both the child and the parent.

Is there any solution to this other than persisting parent hierarchy and children hierarchy in separate tables?

+2  A: 

You need to mark one of the bags as inverse="true". See http://www.hibernate.org/hib_docs/nhibernate/html/collections.html#collections-bidirectional

Isaac Cambron
Thanks so much. I knew it must have been a small setting, but as I'm learning this, I find a lot of this small intricacies come with experience.its now implemented, and tests successful. A++