Storing a Map using JPA

JPA 2.0 supports collections of primitives through the @ElementCollection annotation that you can use in conjunction with the support of java.util.Map collections.
Something like this should work:

@Entity
public class Example {
    @Id long id;
    // ....
    @ElementCollection
    @MapKeyColumn(name="name")
    @Column(name="value")
    @CollectionTable(name="example_attributes", joinColumns=@JoinColumn(name="example_id"))
    Map<String, String> attributes = new HashMap<String, String>(); // maps from attribute name to value

}

See also (in the JPA 2.0 specification)

  • 2.6 – Collections of Embeddable Classes and Basic Types
  • 2.7 Map Collections
  • 10.1.11 – ElementCollection Annotation
  • 11.1.29 MapKeyColumn Annotation

Leave a Comment