是否可以拥有收藏地图?使用下面的代码,用户有一些购买,但我想映射它,因此产品实体(或产品ID)是关键,价值是所有类型产品的购买。
@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 :(得分:0)
JSR317v2.0中的规范仅考虑
的地图集合在地图的键和值部分,似乎
private Map<Long, List<Purchase<Product>>> purchases = new HashMap<>();
对于规范而言,它更复杂。
根据您的要求考虑这样的事情。
但是我想映射它以便产品实体(或产品ID)是关键, 并且值是所有类型产品的购买。
private Map<Product, Purchase> purchases
并使用@MapKey
MapKey注释用于指定特殊情况 map键本身就是主键或持久字段或属性 作为地图价值的实体。 MapKeyClass注释是 指定MapKey时未使用。
注意: @MapKeyColumn(name =“product_id”)只会让列名称对所需的配置不起作用,只需在表格中给出列名称,