问题
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