简体   繁体   中英

Alternative to @ElementCollection using JPA 1.0 for persisting Map<String,String>?

I'm trying to persist a simple Map of attributes as a key value pair for one of my persisted objects. I found a good guide on this matter here . But it only shows how to map when the value of the key is a mapped object (with a 'mapped by' property). My scenario is simpler than this. All I need is to persist a Map<String, String> for a key value pair. I found that I could use @ElementCollection but it is only supported on JPA 2 (the platform I'm working on is still on JPA1).

This is how my code looks like so far:

@Entity
public class MyClass {

    private Map<String, String> attributes;

    @OneToMany
    @MapKey(name="key")
    @JoinTable(name="MyClass_attributes")
    public Map<String, String> getAttributes () {
        return this.attributes;
    }

    public void setAttributes(Map<String, String> attributes) {
        this.attributes = attributes;
    }

}

But I'm getting this error:

Caused by: org.hibernate.AnnotationException: 
Use of @OneToMany or @ManyToMany targeting 
an unmapped class: mypackage.MyClass.attributes[java.lang.String]

Try to create a class for the map's value, like TargetClass. Then the map would be this:

private Map<String, TargetClass> attributes;

In this case the JoinTable doesn't need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM