假设我有一个名为Collect的类,它具有以下属性:
@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 |
+----------------+------------+------------+如果我想要另一个名为“体重”的专栏,比如:
+----------------+------------+------------+------------+
| order_id | quantity | product_id | weight |
+----------------+------------+------------+------------+
| 50006 | 1 | 14 | 3.00 |
| 50006 | 3 | 15 | 5.00 |
+----------------+------------+------------+------------+重量是可变的。也就是说,它没有存储在“product”表中。我想把重量放在这张桌子上。比如:
product.setWeight(5.00);
collectedProducts.put(product, quantity);
repository.save(order);知道我该怎么做吗?我通过创建另一个Map <Product,Weight>并将其映射为一个ElementCollection来实现这一点,但这给了我数据库中的另一个表,我想知道是否有一种简单的方法。
发布于 2016-06-10 05:25:47
创建了另一个名为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;https://stackoverflow.com/questions/37686623
复制相似问题