簡體   English   中英

Map的JPA(休眠)映射。 我應該為java.util.Map映射使用哪些注釋?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM