Hibernate:将多对多映射到Map [英] Hibernate: mapping many-to-many to Map
问题描述
我正在开发一个涉及以下两个实体的应用程序:产品(我们将其命名为X,Y,Z)和材料(a,b,c, ...)。众所周知,每个产品都有一个配方,表明制造这种产品需要什么材料。例如,为了生成一个X,我们需要2 a,6 c和4 d(X = 2a + 6c + 4d)。
I am developing an application which deals with two following entities: Products (let's name it as X, Y, Z) and Materials (a, b, c, ...). It's known that every product has a recipe which indicates what materials are required for making this product. For example, to produce one X we need 2 a, 6 c and 4 d (X = 2a + 6c + 4d).
这是它在数据库表中的反映:
That's how it reflects in a database tables:
Products
id INT
name VARCHAR
...
Materials
id INT
name VARCHAR
...
Recipes
product_id INT
material_id INT
count INT
第三个表中的计数字段是同类材料的系数(2, 6,4从示例)。
The "count" field in the third table is a coefficient for materials of the same kind (2, 6, 4 from the example).
所以我想以这种方式组合产品类:
So I want to compose Product class this way:
public class Product {
...
private Map<Material, Integer> recipe; // How many units of each material we need?
...
}
是一种获取所有必要的方法食谱数据使用Hibernate映射?
Is it a way to fetch all the necessary data for recipe Map using Hibernate? The separate configuration approach (without annotations) is preferred.
推荐答案
由于没有人发布解决方案而没有注释,我会显示解决方案与JPA 2.0 @ElementCollection
注释:
Since nobody posted the solution without annotations, I'll show the solution with JPA 2.0 @ElementCollection
annotation:
@ElementCollection
@CollectionTable(name = "Recipes",
joinColumns = @JoinColumn(name = "product_id"))
@MapKeyJoinColumn(name = "material_id")
@Column(name = "count")
private Map<Material, Integer> recipe;
另请注意,由于您的地图的类的值为整数
,没有注释的解决方案可能被记录为集合映射而不是实体关系映射。
Also note that since class of values of your map is Integer
, solution without annotations is likely to be documented as "collection mapping" rather than "entity relationship mapping".
这篇关于Hibernate:将多对多映射到Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!