多対 1 の
親にはプロパティ Child が含まれており、子は複数の親からリンクされている場合があります。
class Parent
{
public virtual MyItem Child { get; set; }
}
<class name="Parent">
<many-to-one name="Child" column="MyItemId" />
</class>
結合テーブルを使用した多対多
親には子のコレクションが含まれ、子は複数の親からリンクされている場合があります。
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 メソッドに切り替えます。