Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 899
VB_ Avatar asked Jan 17 '17 12:01

VB_


1 Answers

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>)
like image 143
Maciej Kowalski Avatar answered Oct 21 '22 11:10

Maciej Kowalski