2016-06-07 53 views
0

比方说,我有一个名为类收集具有以下属性:映射从地图的关键属性上元素集合

@ElementCollection 
@MapKeyJoinColumn(name="product_id") 
@Column(name="quantity") 
@CollectionTable([email protected](name="order_id")) 
//The value of the map stores the quantity of each product. 
private Map<Product, Integer> collectedProducts; 

这给了我下面的表格:

+----------------+------------+------------+ 
|  order_id | quantity | product_id | 
+----------------+------------+------------+ 
|   50006 |   1 |   14 | 
|   50006 |   3 |   15 | 
+----------------+------------+------------+ 

如果我想要另一个名为“重量”的列:

+----------------+------------+------------+------------+ 
|  order_id | quantity | product_id |  weight | 
+----------------+------------+------------+------------+ 
|   50006 |   1 |   14 |  3.00 | 
|   50006 |   3 |   15 |  5.00 | 
+----------------+------------+------------+------------+ 

重量可变的地方。也就是说,它不存储在'产品'表中。我想设置重量并存储在此表中。喜欢:

product.setWeight(5.00); 
collectedProducts.put(product, quantity); 
repository.save(order); 

任何想法我怎么能做到这一点?我通过创建另一个Map <Product,Weight>并将其映射为ElementCollection来实现此目的,但是这给了我另一个数据库中的表,并且我想知道是否有简单的方法。

+0

创建一个额外的实体想要添加“额外的列”,并映射真实的数据(权重+数量)。 JPA在这里没有什么特别的...让你的O-O权利,所有将映射罚款。 –

回答

0

创造了另一个类称为Quantity和anotted它作为@Embeddable

@Embeddable 
    public class Quantity { 

    private int quantity; 
    private double weight; 

//getters and setter ommited; 

    } 

然后在我的Collect类,只映射到这个新类作为我的地图值类型:如果您

@ElementCollection 
@MapKeyJoinColumn(name="product_id") 
@CollectionTable([email protected](name="order_id")) 
Map<Product,Quantity> collectedProducts;