I have a simple picture database where I have albums that can have many subalbums. I have a following mapping for class Album
Code:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
<class name="DB.Data.Album, DB.Data" table="ALBUM">
<id name="Id" column="ID" unsaved-value="-1">
<generator class="sequence">
<param name="sequence">ALBUM_ID_GEN</param>
</generator>
</id>
<property name="Name" column="ALBUM_NAME" />
<property name="Description" column="ALBUM_DESCRIPTION" />
<many-to-one name="Parent" column="PARENT_ID" class="DB.Data.Album, DB.Data" />
</class>
</hibernate-mapping>
Following is the Album class
Code:
using System;
namespace DB.Data
{
/// <summary>
/// Description of Album.
/// </summary>
public class Album
{
Album()
{
}
public Album(string name)
{
this.name = name;
}
public Album(string name, string description)
{
this.name = name;
this.description = description;
}
int id = -1;
public virtual int Id {
get {
return id;
}
set {
id = value;
}
}
Album parent;
public Album Parent {
get {
return parent;
}
set {
parent = value;
}
}
string name;
public virtual string Name {
get {
return name;
}
set {
name = value;
}
}
string description;
public virtual string Description {
get {
return description;
}
set {
description = value;
}
}
public override string ToString()
{
return Name;
}
}
}
I also have a data manager which can provide me a collection of objects as follows:
Code:
public T GetBy(string prop, object val)
{
using(NHibernate.ISession sess = factory.OpenSession())
{
NHibernate.Expression.ICriterion crit;
if(val != null)
{
crit = NHibernate.Expression.Expression.Eq(prop, val);
}
else
{
crit = NHibernate.Expression.Expression.IsNull(prop);
}
return (T)sess.CreateCriteria(typeof(T))
.Add(crit)
.UniqueResult();
}
}
Then I ask data manager for all albums having "Album" property set to null. Then I am recursing throug every item and so on. This way I have a full tree of albums.
I know that this is not optimal and could be improved but it works perfectly. Hope this helps you :)