Many-to-One
家長包含物業孩子,孩子可以從幾個家長聯繫起來。
class Parent
{
public virtual MyItem Child { get; set; }
}
<class name="Parent">
<many-to-one name="Child" column="MyItemId" />
</class>
Many-to-Many with a join table
家長包含的子集,孩子們可以從幾個家長聯繫起來。
class Parent
{
public virtual IList<MyItem> Children { get; set; }
}
<class name="Parent">
<bag name="Children" table="parent_myitem">
<key column="parentid" />
<many-to-many class="MyItem" column="MyItemId" />
<bag>
</class>
Criteria Querying
// find Parent with child named "foo".
DetachedCriteria.For<Parent>()
.CreateAlias("Child", "c")
.Add(Restrictions.Eq("c.Name", "foo"));
// find Parent with particular child
DetachedCriteria.For<Parent>()
.Add(Restrictions.Eq("Child", child));
// find Parent with one of children named "foo".
DetachedCriteria.For<Parent>()
.CreateAlias("Children", "c")
.Add(Restrictions.Eq("c.Name", "foo"));
// find a "page" of children for a parent
DetachedCriteria.For<Parent>()
.Add(Restrictions.Eq("Id", parent.Id))
.CreateAlias("Children", "c")
.SetFirstResult(1041)
.SetMaxResults(20)
.GetExecutableCriteria(session)
.List<MyItem>();
這最後的查詢可能會或可能不會被更有效地利用只是延遲加載上首次訪問整個兒集合,然後索引到它後來的「做頁面」。這取決於您的數據和使用情況。
除非我先知道孩子的收藏會是巨大的,否則我會首先進入懶惰的負載路線。如果時間和profiling顯示嚴重緩慢,那麼我會切換到標準方法。
偉大的問題。很棒,正是我想問的。 – Slavo