您的示例严格来说是一个Many-To-Many
映射。
public class Foo {
public virtual int Id { get; set; }
public virtual IList<Cat> Cats { get; set; }
}
// there is no Bar entity in this example; it is a cross-reference table used by nhibernate, but there is no entity in your domain
public class Cat {
public virtual int Id { get; set; }
public virtual IList<Foo> Foos { get; set; }
}
映射:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Models"
namespace="Models">
<class name="Foo" table="foo">
<id name="Id" column="Id">
<generator class="identity" />
</id>
<bag name="Cats" table="bar">
<key column="FooId"></key>
<many-to-many column="CatId" class="Cat" />
</bag>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Models"
namespace="Models">
<class name="Cat" table="cat">
<id name="Id" column="Id">
<generator class="identity" />
</id>
<bag name="Foo" table="bar">
<key column="CatId"></key>
<many-to-many column="FooId" class="Foos" />
</bag>
</class>
</hibernate-mapping>
但是,如果 Foos 和 Cats 之间的关系比关系更有意义(例如,您需要向 Bar 添加其他属性),您将执行以下操作:
public class Foo {
public virtual int Id { get; set; }
public virtual IList<Bar> Bars { get; set; }
}
public class Bar
{
public virtual Foo Foo { get; set; }
public virtual Cat Cat { get; set; }
}
public class Cat {
public virtual int Id { get; set; }
public virtual IList<Bar> Bars { get; set; }
}
// you can get all Cats for a Foo via Foo.Bars and vice versa
映射:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Models"
namespace="Models">
<class name="Foo" table="foo">
<id name="Id" column="Id">
<generator class="identity" />
</id>
<bag name="Bars" inverse="true">
<key column="CatId"></key>
<one-to-many class="Bar"/>
</bag>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Models"
namespace="Models">
<class name="Cat" table="cat">
<id name="Id" column="Id">
<generator class="identity" />
</id>
<bag name="Bars" inverse="true">
<key column="FooId"></key>
<one-to-many class="Bar"/>
</bag>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Models"
namespace="Models">
<class name="Bar" table="bar">
<composite-id>
<key-many-to-one class="Foo" name="Foo" column="FooId" />
<key-many-to-one class="Cat" name="Cat" column="CatId" />
</composite-id>
</class>
</hibernate-mapping>
对不起,如果我的 HBM 标记生锈了;我习惯于通过代码进行映射。