logo image

How to store Map<String, String> using JPA

I want to store properties for a user. My pojo looks like below

@Table(name = "users")
public class User {
	        name = "usersSequenceGenerator",
	        strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
	        parameters = {
	                @Parameter(name = "sequence_name", value = "usersSequence"),
	                @Parameter(name = "initial_value", value = "1"),
	                @Parameter(name = "increment_size", value = "1")
	@GeneratedValue(generator = "usersSequenceGenerator")
    private long id;
    private String name;
    private int age;
    private String email;
    private Map<String, String> properties;

    ........ Setters & Getters

How to store these properties?

1 Answer

2 years ago by

All you need to do is annotate the properties variable with @ElementCollection and mention column names etc. Refer the following code

    @CollectionTable(name="user_properties", [email protected](name="id"))
    private Map<String, String> properties;

This will create another table with name user_properties and put your properties there, it also adds a column with name 'id' and creates a forign key to your mail collection's id

2 years ago by Megamind