Hibernate persist Map<String, String> without referencing another tables

强颜欢笑 提交于 2019-12-09 05:34:52

问题


Could you please help me to persist map of strings with Hibernate?

Map values come from client and are random, so I don't want to store separate table for map's values

Exception

Caused by: org.hibernate.AnnotationException: Associated class not found: java.lang.String

Code

@Entity
public class UserConfig {

    @Id
    @SequenceGenerator(sequenceName = "CONFIG_SEQ", name = "ConfigSeq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ConfigSeq")
    private Long id;

    @ElementCollection(targetClass = String.class)
    @CollectionTable(name = "MAP")
    @MapKey(name="key")
    @Column(name="value")
    private Map<String, String> map;

Update

Could you please also explain how to persist Map<MyEnum, String> , if MyEnum is an unmapped class?


回答1:


According to the specification, you should annotate the map like this:

    @ElementCollection(targetClass = String.class)
    @CollectionTable(name = "MAP")
    @MapKeyColumn(name="key")
    @Column(name="value")
    private Map<String, String> map;

So @MapKeyColumn, instead of @MapKey.

This is the way you should annotate the map when its defined as:

private Map<Basic, Basic> map; // (i.e. Map<String, String>)

You use the @MapKey annotation when you have map defined as:

private Map<Basic, Entity> map; // (i.e. Map<String, User>)

And finally, you use @MapKeyEnumerated annotation when you have map defined ad:

private Map<Enumeration, Basic> map; // (i.e. Map<MyEnum, String>)


来源:https://stackoverflow.com/questions/41697714/hibernate-persist-mapstring-string-without-referencing-another-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!