映射的JPA(Hibernate)映射。我应该使用哪些注释来进行java.util.Map映射?

时间:2017-01-22 10:12:10

标签: java hibernate jpa mapping many-to-many

表格结构:

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

更新。有两种正确的解决方案(来自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;

2 个答案:

答案 0 :(得分:0)

您选择的JPA提供商的文档是否包含如何映射您的地图字段?您可以在DataNucleus JPA提供的this documentation中看到它的描述。简单来说,您需要包含

@ElementCollection
@JoinTable
Map<Product, Integer> productQuantityMap;

(以及任何其他注释,如果你想配置架构,但这些是必要的位)。

答案 1 :(得分:0)

尝试此配置。 @ElementCollection而不是@ManyToMany和@CollectionTable而不是@JoinTable

@ElementCollection
@CollectionTable(name = "products_to_orders"        
@MapKeyJoinColumn(name = "product_id")
@Column(name = "product_quantity")
private Map<Product, Integer> productQuantityMap;