より明確にするために、同様のシナリオを示します。
シナリオ1:
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
ファイルマッピングにはこの関係の実装が含まれず、関係の両側にある2つの多対多のマッピング(2つのバッグまたは2つのクラスからの2つのセット)で表されます。次のように:
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>
Orders.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がテーブルのinProducts
と多対多の関係にあることを意味します。Order_Id
Orders
tag
バッグ内のテーブルは、関係の中間点である多対多のマッピングテーブルであり、バッグ内は、テーブルに関連するOrder_Id
FKであることに注意してください。Order_Products
Products
2つのバッグの名前は、Productsクラスの多対多の関係を表す2つのクラスの2つのコレクションの名前です。
public virtual IList<Orders> Orders
{
get;
set;
}
クラスにはOrders
、製品のリストがあります。
public virtual IList<Products> Products
{
get;
set;
}
Order_Products.hbmでは、この関係に対して何もする必要はありませんがOrder_Products
、外部キーのみが含まれ、追加のプロパティがない場合、たとえば数量がない場合は、テーブルをマップする必要はありません。財産:
<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>
他の2つのシナリオでは、composite-key(a <composite-id>
)を使用して追加の複合主キーをマップすることを除いて、同じマッピングに従うと思いますが、マッピングは同じです。
他の2つのシナリオでは、正直なところ、私は複合IDのマッピングを自分で試しませんでしたが、関係は同じようになり、複合キーは関係に影響を与えないと思いますが、Hibernateチームは強く影響しません複合キーの使用をお勧めします。
簡単にするために、xmlマッピングの多くのコードを無視しました。