How to store Map<String, String> using JPA
I want to store properties for a user. My pojo looks like below
@Entity
@Table(name = "users")
public class User {
@GenericGenerator(
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")
}
)
@Id
@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
7 years ago by Divya
All you need to do is annotate the properties variable with @ElementCollection
and mention column names etc. Refer the following code
@ElementCollection
@MapKeyColumn(name="name")
@Column(name="value")
@CollectionTable(name="user_properties", joinColumns=@JoinColumn(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
7 years ago by Karthik Divi