Storing a Map<String,String> using JPA

JavaJpaOrmJpa 2.0

Java Problem Overview


I am wondering if it is possible using annotations to persist the attributes map in the following class using JPA2

public class Example {
    long id;
    // ....
    Map<String, String> attributes = new HashMap<String, String>();
    // ....
}

As we already have a pre existing production database, so ideally the values of attributes could map to the following existing table:

create table example_attributes {
    example_id bigint,
    name varchar(100),
    value varchar(100));

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

  @ElementCollection(fetch = FetchType.LAZY)
  @CollectionTable(name = "raw_events_custom", joinColumns = @JoinColumn(name =     "raw_event_id"))
  @MapKeyColumn(name = "field_key", length = 50)
  @Column(name = "field_val", length = 100)
  @BatchSize(size = 20)
  private Map<String, String> customValues = new HashMap<String, String>();

This is an example on how to set up a map with control over column and table names and field length.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncorydorasView Question on Stackoverflow
Solution 1 - JavaPascal ThiventView Answer on Stackoverflow
Solution 2 - JavawciesielView Answer on Stackoverflow