从Element Collection上的Map Key映射属性

时间:2016-06-07 18:23:11

标签: java hibernate jpa spring-data

假设我有一个名为收集的课程,其中包含以下属性:

@ElementCollection
@MapKeyJoinColumn(name="product_id")
@Column(name="quantity")
@CollectionTable(joinColumns=@JoinColumn(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 |
+----------------+------------+------------+

如果我想要另一个名为'weight'的列,如果:

,该怎么办?
+----------------+------------+------------+------------+
|       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来实现此目的,但这给了我数据库中的另一个表,我想知道是否有一种简单的方法。

1 个答案:

答案 0 :(得分:0)

创建了另一个名为Quantity的类,并将其标记为@Embeddable

    @Embeddable
    public class Quantity {

    private int quantity;
    private double weight;

 //getters and setter ommited;

    }

然后在我的Collect类中,只将这个新类映射为我的地图值类型:

@ElementCollection
@MapKeyJoinColumn(name="product_id")
@CollectionTable(joinColumns=@JoinColumn(name="order_id"))
Map<Product,Quantity> collectedProducts;
相关问题