我试过
@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)
任何想法?
答案 0 :(得分:23)
嗯,错误信息非常明确:Double
不是实体。如果要映射基本元素的集合,请使用CollectionOfElement
注释(来自Hibernate)或ElementCollection
注释(来自JPA 2.0)。
因此,假设您正在使用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
JoinTable
设置父级键的列名称
MapKey
Column