为了更清楚,我会给你一个类似的场景:
场景一:
Table Products
Product_Id(PK)
Product_Name
Price
Table Orders
Order_Id(PK)
Order_Date
Total
Table Order_Products
Order_Product_Id(PK) (Surrogate key)
Order_Id(FK)
Product_Id(FK)
Quantity
Orders
在这个域中,我们在和表之间有一个多对多的关系Products
,如下所示:
当我们映射这种多对多关系时,Order_Products
文件映射将不包含该关系的任何实现,它将由关系两侧的两个多对多映射(两个包或两个类的两个集合)表示如下:
对于 Products.hbm:
<class name="Products" table="Products">
<id name="Product_Id" column="Product_Id">
<generator class="native"/>
</id>
<bag name="Orders" generic="true" table="Orders_Products">
<key column="Product_Id"/>
<many-to-many column="Add_Orders_Id" class="Orders"/>
</bag>
...and other properties
</class>
订单.hbm:
<class name="Orders" table="Orders">
<id name="Order_Id" column="Order_Id">
<generator class="native"/>
</id>
<bag name="Products" generic="true" table="Order_Products">
<key column="Orders_Id"/>
<many-to-many column="Product_Id" class="Products"/>
</bag>
...
这意味着Product_Id
from 表与表中Products
的 具有多对多关系。Order_Id
Orders
注意,包中的表tag
是多对多映射表,是关系的中间点,包内是与表相关Order_Id
的FK 。Order_Products
Products
两个包的名字就是Products类中代表多对多关系的两个类中的两个集合的名字:
public virtual IList<Orders> Orders
{
get;
set;
}
在Orders
课堂上,您有一个产品列表:
public virtual IList<Products> Products
{
get;
set;
}
Order_Products
在 Order_Products.hbm 中,您根本不需要为这种关系做任何事情,但是如果表仅包含外键并且没有其他属性,例如如果它没有 Quantity ,则您不必映射表财产:
<class name="Order_Products" table="Order_Products">
<id name="Order_Product_Id" column="Order_Product_Id">
<generator class="native" />
</id>
<property name="Quantity" type="Decimal" column="Quantity" />
</class>
在其他两种情况下,我认为您将遵循相同的映射,除了您将使用复合键(a <composite-id>
)来映射附加的复合主键,但映射将是相同的。
对于另外两个场景,老实说,我自己没有尝试过复合id的映射,但我认为关系会是相同的方式,复合键不会影响关系,但是Hibernate团队强烈不这样做推荐使用复合键。
为了简单起见,我忽略了 xml 映射中的很多代码。