2014-02-16 46 views
0

是否有可能擁有一個集合的地圖?對於下面的代碼,用戶有一些購買,但我想映射它,所以產品實體(或產品ID)是關鍵,而這些值是所有類型產品的購買。JPA,Hibernate,使用@MapKeyColumn的集合地圖

@Entity 
public class User { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Long id; 

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = Purchase.class, orphanRemoval = true) 
    @JoinColumn(name = "user_id", updatable = false) 
    @MapKeyColumn(name = "product_id") 
    private Map<Long, List<Purchase<Product>>> purchases = new HashMap<>(); 

} 

@Entity 
public class Product { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

} 

@Entity 
public class Purchase<T extends Product> implements Serializable { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    Long id; 

    @ManyToOne 
    @JoinColumn(name = "user_id", referencedColumnName = "id") 
    private User user; 

    @ManyToOne(targetEntity = Prodect.class) 
    @JoinColumn(name = "product_id", referencedColumnName = "id") 
    private T product; 

    @Column(name = "purchase_date") 
    private Date purchaseDate; 

} 

異常;

org.springframework.orm.hibernate3.HibernateSystemException: could not get a field value by reflection getter of test.domain.Purchase.id; nested exception is org.hibernate.PropertyAccessException: could not get a field value by reflection getter of test.domain.Purchase.id 
... 
Caused by: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of test.domain.Purchase.id 
... 
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field test.domain.Purchase.id to java.util.ArrayList 

回答

0

規格在JSR317v2.0只考慮

  1. 基本型
  2. 嵌入型
  3. 實體的地圖收藏。

在地圖的鑰匙,和值部分,似乎

private Map<Long, List<Purchase<Product>>> purchases = new HashMap<>(); 

它是爲規範的目的更加複雜。

請考慮爲您的要求有這樣的事情。

,但我想它映射這樣的產品實體(或產品ID)是關鍵, 和值是一種產品的所有采購。

private Map<Product, Purchase> purchases 

並使用@MapKey

映射鍵註釋用於指定其中 地圖鍵本身是主鍵或 實體持久字段或屬性的特殊情況是地圖的價值。在指定MapKey時MapKeyClass註釋是 。

注:@MapKeyColumn(NAME = 「PRODUCT_ID」)只給出了列名不執行任何操作與所需的配置只是在表中給出的列名,