我试过了
@ManyToMany(cascade = CascadeType.ALL) Map<String, Double> data = new HashMap<String, Double>();
但它产生错误:
org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.company.Klass.data[java.lang.Double] at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1016) at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:567) at org.hibernate.cfg.annotations.MapBinder$1.secondPass(MapBinder.java:80) at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:43) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1130) at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:296) at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1115)
任何的想法?
好吧,错误消息很清楚:Double不是实体。如果要映射基本元素的集合,请使用CollectionOfElement批注(来自Hibernate)或ElementCollection批注(来自JPA 2.0)。
Double
CollectionOfElement
ElementCollection
因此,假设您使用的是Hibernate Annotations 3.4,请尝试以下操作:
@CollectionOfElements(targetElement = Double.class) @org.hibernate.annotations.MapKey(targetElement = String.class) Map data;
或者,使用泛型时:
@CollectionOfElements Map<String, Double> data;
如果您使用的是Hibernate Annotations 3.5+,则更喜欢JPA 2.0注释:
@ElementCollection(targetClass = Double.class) @MapKeyClass(String.class) Map data;
@ElementCollection Map<String, Double> data;
您知道如何自定义“ ELEMENT”和“ MAPKEY”列名称吗?
您可以完全自定义结果。我认为以下示例展示了所有内容:
@CollectionOfElements(targetElement = Double.class) @JoinTable(name = "COLLECTION_TABLE", joinColumns = @JoinColumn(name = "PARENT_ID")) @org.hibernate.annotations.MapKey(targetElement = String.class, columns = @Column(name = "SOME_KEY")) @Column(name = "SOME_VALUE") private Map data;
Map
JoinTable
JoinColumn
MapKey
Column