如何映射Map <String,Double>

Nha*_*lio 9 java orm hibernate jpa hibernate-annotations

我试过了

@ManyToMany(cascade = CascadeType.ALL)
Map<String, Double> data = new HashMap<String, Double>();
Run Code Online (Sandbox Code Playgroud)

但它会产生错误:

   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)
Run Code Online (Sandbox Code Playgroud)

任何的想法?

Pas*_*ent 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;
Run Code Online (Sandbox Code Playgroud)

或者,使用泛型时:

@CollectionOfElements
Map<String, Double> data;
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Hibernate Annotations 3.5+,则更喜欢JPA 2.0注释:

@ElementCollection(targetClass = Double.class)
@MapKeyClass(String.class)
Map data;
Run Code Online (Sandbox Code Playgroud)

或者,使用泛型时:

@ElementCollection
Map<String, Double> data;
Run Code Online (Sandbox Code Playgroud)

参考


你知道如何自定义"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;
Run Code Online (Sandbox Code Playgroud)
  • Map使用的定义了集合表的名称JoinTable
    • 为重点,以父列的名称用设置JoinColumnJoinTable
  • 地图键的列名称在.中定义 MapKey
  • 使用地图定义地图值的列名称 Column