views:

79

answers:

1

I have an object called MyItem that references children in the same item. How do I set up an nhibernate mapping file to store this item.

public class MyItem
    {
    public virtual string Id {get;set;}

    public virtual string Name {get;set;}

    public virtual string Version {get;set;}

    public virtual IList<MyItem> Children {get;set;}    

    }

So roughly the hbm.xml would be:

   <class name="MyItem"  table="tb_myitem">

      <id name="Id" column="id" type="String" length="32">
         <generator class="uuid.hex" />
      </id>

      <property name="Name"     column="name" />
      <property name="Version"  column="version" />

      <bag name="Children" cascade="all-delete-orphan" lazy="false">
         <key column="children_id" />
         <one-to-many class="MyItem"
                      not-found="ignore"/>
      </bag>      

   </class>

This wouldn't work I don't think. Perhaps I need to create another class, say MyItemChildren and use that as the Children member and then do the mapping in that class?

This would mean having two tables. One table holds the MyItem and the other table holds references from my item. NOTE: A child item could have many parents.

A: 

I have this working with eagerly loading the objects.

I am able to load the 'MyItem' object and with it, the children (Dependant) 'MyItem' objects as well.

The following is my C# class

using Iesi.Collections.Generic;

namespace Sample
   {
   public class MyItem
      {
      public virtual string Id { get; set; }
      public virtual string Name { get; set; }
      public virtual string Version { get; set; }

      public virtual ISet<MyItem> Dependants { get; set; }

      }
   }

The Dependants are the collection of children that are dependant on the parent. Each MyItem will have many MyItem children. These are stored in an IESI ISet<>.

The hibernate mapping file is:

   <class name="Sample.MyItem, Sample" table="myitem">
      <id name="Id" column="id" type="String" length="32">
         <generator class="uuid.hex" />
      </id>

      <property name="Name"     column="name"     type="String" length="80"/>
      <property name="Version"  column="version"  type="String" length="25"/>

      <set name="Dependants" table="myitemhierarchy" >
         <key column="parentid" />
         <many-to-many class="Sample.MyItem, Sample" column="childid" />
      </set>
   </class>

This article helped immensely: http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/05/14/how-to-map-a-tree-in-nhibernate.aspx

AdamC