[英]JPA (Hibernate) mapping of Map. What annotations should I use for java.util.Map mapping?
表结构:
TABLE products (id (PK), name, price);
TABLE orders (id (PK), customer_id, user_id);
//product_quantity is quantity of product in particular order
TABLE products_to_orders (product_id, order_id, product_quantity
PRIMARY KEY (product_id, order_id),
FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE,
FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE
);
这是我的Order.java
:
@Entity
@Table(name = "orders")
public class Order extends BaseEntity {
...
//this map holds Products and their quantities in order;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "products_to_orders"
,joinColumns = @JoinColumn(name = "order_id")
,inverseJoinColumns = @JoinColumn(name = "product_id") //it seems that i don't need this line
)
@MapKeyJoinColumn(name = "product_id")
@Column(name = "product_quantity")
private Map<Product, Integer> productQuantityMap;
...
我使用这些注释的映射不起作用。 它给出了一个例外:
原因:org.hibernate.AnnotationException:使用@OneToMany或@ManyToMany定位未映射的类:com.malikov.shopsystem.model.Order.productQuantityMap [java.lang.Integer]
因此,我无法管理如何正确注释此地图。 非常感谢您的帮助! 这是我在GitHub上的代表的链接https://github.com/malikov-yurii/online-shop-management-system.git
UPDATE。 有两种正确的解决方案(来自Neil和Maciej):
Variation 1:
@ElementCollection(fetch = FetchType.EAGER)
@JoinTable(
name = "products_to_orders"
,joinColumns = @JoinColumn(name = "order_id")
)
@MapKeyJoinColumn(name = "product_id")
@Column(name = "product_quantity")
private Map<Product, Integer> productQuantityMap;
Variation 2
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "products_to_orders")
@MapKeyJoinColumn(name = "product_id")
@Column(name = "product_quantity")
private Map<Product, Integer> productQuantityMap;
您选择的JPA提供程序的文档中是否包括如何映射“地图”字段? 您可以在DataNucleus JPA提供的本文档中看到它的描述。 简单来说,您需要包括
@ElementCollection
@JoinTable
Map<Product, Integer> productQuantityMap;
(以及要配置架构的所有其他注释,但这是必不可少的)。
试试这个配置。 @ElementCollection代替@ManyToMany和@CollectionTable代替@JoinTable
@ElementCollection
@CollectionTable(name = "products_to_orders"
@MapKeyJoinColumn(name = "product_id")
@Column(name = "product_quantity")
private Map<Product, Integer> productQuantityMap;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.