9

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 Answer 1

20

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>)
Sign up to request clarification or add additional context in comments.

5 Comments

additionally, targetClass can also be omitted if we are using generics
@MaciejKowalski thanks for your answer! Could you plsease also explain how to make Map<MyEnum, String> , if MyEnum is unmapped class?
Based on my notes while i was preparing for the JPA Certificate that is possible. Please find the answer in the edited post.
Anyone know if I can do this in XML mappings with Hibernate?
may I use Map<String, Object>?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.