多对一
Parent 包含一个属性 Child,孩子可能来自多个父母。
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
Parent 包含一个 Child 的集合,这些孩子可能来自多个父母。
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>
条件查询
// 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>();
通过在第一次访问时延迟加载整个子集合,然后在后续“页面”上对其进行索引,最后一个查询可能会或可能不会更有效地完成。这取决于您的数据和使用情况。
除非我事先知道子集合会很大,否则我会先走延迟加载路线。如果计时和分析显示严重缓慢,那么我会切换到 Criteria 方法。