【问题标题】:Mapping attributes from Map Key on Element Collection从元素集合上的映射键映射属性
【发布时间】:2016-06-07 18:23:10
【问题描述】:

假设我有一个名为 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.setWeight(5.00);
collectedProducts.put(product, quantity);
repository.save(order);

知道我该怎么做吗?我通过创建另一个Map &lt;Product,Weight&gt; 并将其映射为ElementCollection 来实现这一点,但这给了我数据库中的另一个表,我想知道是否有一个简单的方法。

【问题讨论】:

  • 如果要添加“额外的列”,请创建一个额外的实体,并映射真实数据(重量+数字)。 JPA 在这里没有做任何特别的事情......让你的 O-O 正确,一切都会很好。

标签: java hibernate jpa spring-data


【解决方案1】:

创建了另一个名为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;

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    相关资源
    最近更新 更多