Alejandro Germenos
Alejandro Germenos

Reputation: 15

POJO with a Hashmap in Hibernate

I have an object with properties like this:

@Entity
@Table (name="person")
class Person {
    @Id
    @SequenceGenerator(name="pk_sequence",sequenceName="user_id_seq")
    @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="pk_sequence")
    @Column(name="id", unique=true, nullable=false)
    private int id;
    @Column(name="age")
    int age;
    @Column(name="email")
    String email;
}

Now the tricky part. I want a map to be added to this object. The idea is that the map has properties not defined in the table, but dynamically assigned. They are stored in a table with the same person id, so I can link them... the question is how can I map this in Hibernate? I thought of using inheritance, but I'm not sure it's the way to go... or even how do I do that with a map.

Upvotes: 0

Views: 380

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

I don't see what inheritance has to do with your problem. All you need to do is to map the map (!) as an element collection:

@ElementCollection
private Map<String, String> properties = new HashMap<>();

If you want to customize the mapping (choose the table name, the column name for the key, the column name for the value, the column name for the foreign key pointing back to the owning Person), then use the appropriate annotations:

@ElementCollection
@CollectionTable(name = "PERSON_PROPERTY")
@MapKeyColumn(name = "NAME")
@Column(name = "VALUE")
@JoinColumn(name = "PERSON_ID")
private Map<String, String> properties = new HashMap<>();

Upvotes: 2

Related Questions