Tuesday, 9 July 2013

Using a Map to represent an entity as name and value pair in JPA

Lets imagine there is a situation when there is a table in the database which contains some attributes as name and value pairs. Having this entity as a collection referencing to the other table using @OneToMany mapping and then looping through it by adding attributes: name as a key and value as a value into the Map is pretty straightforward, but persuading JPA to do the job requires a little bit more work. This tutorial will show exactly how to make this happen using plain JPA. Please note that all the annotation used in the following classes are coming from javax.persistence package. All of them are standard JPA annotations and none of them is framework specific.

Make sure that equals and hasCode methods are overridden as this is the pirmary key of the Attribute entity and must be unique. And finally we need to create an entity which will hold the actual Map. Lets name it AttributeGroup: