Java – how to map maps

I tried

@ManyToMany(cascade = CascadeType.ALL)
Map<String,Double> data = new HashMap<String,Double>();

But it produces errors:

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)

Any ideas?

Solution

Then, the error message is clear: double is not an entity If you want to map a collection of base elements, use the collectionofelement annotation (from hibernate) or elementcollection annotation (from JPA 2.0)

So, suppose you use hibernate annotations 3.4, try this:

@CollectionOfElements(targetElement = Double.class)
@org.hibernate.annotations.MapKey(targetElement = String.class)
Map data;

Or, when using generics:

@CollectionOfElements
Map<String,Double> data;

If you use hibernate annotations 3.5, you prefer JPA 2.0 annotations:

@ElementCollection(targetClass = Double.class)
@MapKeyClass(String.class)
Map data;

Or, when using generics:

@ElementCollection
Map<String,Double> data;

reference resources

>Hibernate note 3.4 reference guide

> 2.4. 6.2. 2. Map > 2.4. 6.2. 5. Collection of element or composite elements

>JPA 2.0 specification

> Section 11.1. 12 "elementcollection Annotation" > section 11.1 Section 28 "mapkeyclass Annotation"

You can completely customize the results I think the following example demonstrates everything:

@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;

>Use jointable to define the name of the set table of the map

>Use joincolumn in jointable to set the name of the column of the parent object

>Column name of map key defined in mapkey > name of column using column to define map value

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>