【发布时间】:2016-11-29 00:51:28
【问题描述】:
不用担心持久性,我设计了一个类来保存由(不同大小的)容器映射的不同产品的数量,产品可以保存在这些容器中
class Inventory {
Long id;
Map <Long, Map<Long,Integer>> productQuantityByContainer; // ProductId->(ContainerId -> quantity)
}
Product 和 Container 类为
class Product {
Long id;
String name;
}
class Container {
Long id;
Double size;
}
后两者具有与其相应数据库表的直接 Hibernate 映射。我需要使用 Hibernate 映射文件(hbm.xml)并且我的数据库有以下信息(不考虑 Hibernate 的约束):
Product table
--------------
ID|Name
1 Milk
2 Orange Juice
Container table
---------------
ID |Size(oz)
10 32
11 64
Inventory table (first 2 columns form the PK)
---------------
Product-ID(FK) | Container-ID(FK) | Quantity
1 10 25
1 11 15
2 10 33
我的问题是:我了解 Hibernate 不允许集合映射的持久性。因此,要使 Hibernate 持久保存我的 Inventory 类中的信息,我的设计和映射如下所示就足够了吗? (我使用两个同名映射表创建了两个类 ContainerQuantity 和 Quantity,如下所示)请在下面评论/检查我的 hbm 映射。
class Inventory { // <--- Redesigned --->
Long id;
Map <Long, ContainerQuantity> cqsByProduct; // ProductId->ContainerQty
}
<class name="Inventory"> <!-- hbm mapping -->
<id name="id"/>
<map name="cqsByProduct">
<key column="Inventory_ID" not-null="true"/>
<map-key column="Product_ID"
<one-to-many class="ContainerQuantity"/>
</map>
</class>
Inventory table (in Database)
---------------
id
90210
90211
class ContainerQuantity {
Long id;
Map<Long,Integer> quantitiesByContainer;
}
<class name="ContainerQuantity"> <!-- hbm mapping -->
<id name="id"/>
<map name="quantitiesByContainer">
<key column="CQ_ID" not-null="true"/>
<map-key column="Container_ID"
<one-to-many class="Quantity"/>
</map>
</class>
ContainerQuantity table (for holding the cqsByProduct collection)
------------------------
id | Product_ID | Inventory_ID (FK to collection owner)
101 1 90210
102 1 90210
103 2 90210
class Quantity {
Integer quantity;
Container container;
ContainerQuantity cq;
}
<class name="Quantity"> <!-- hbm mapping -->
<composite-id>
<key-many-to-one name="container" class="Container" column="Container_ID" />
<key-many-to-one name="cq" class="ContainerQuantity" column="CQ_ID" />
</composite-id>
</class>
Quantity table (for holding quantitiesByContainer collection)
--------------------
Container_ID(FK) | Quantity | CQ_ID (FK to collection owner)
10 25 101
11 15 102
10 33 103
【问题讨论】:
标签: hibernate