使用JPA存储Map <String,String>

cor*_*ras 96 java orm jpa jpa-2.0

我想知道是否可以使用注释attributes使用JPA2在以下类中持久保存地图

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

由于我们已经有一个预先存在的生产数据库,所以理想情况下,值attributes 可以映射到以下现有表:

create table example_attributes {
    example_id bigint,
    name varchar(100),
    value varchar(100));
Run Code Online (Sandbox Code Playgroud)

Pas*_*ent 188

JPA 2.0通过@ElementCollection注释支持基元集合,您可以将其与java.util.Map集合的支持结合使用.这样的事情应该有效:

@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

}
Run Code Online (Sandbox Code Playgroud)

另请参阅(在JPA 2.0规范中)

  • 2.6 - 可嵌入类和基本类型的集合
  • 2.7地图集合
  • 10.1.11 - ElementCollection注释
  • 11.1.29 MapKeyColumn注释

  • 就是这样.我一直在尝试使用"@ElementCollection"注释,但无法使其正常工作! (5认同)
  • 可能值得一提的是`example_attributes`应该有一个复合键`(example_id,name)` - 这就是hbm2ddl将从上面生成的. (3认同)
  • 使用MariaDB,我遇到了“指定密钥太长;最大密钥长度是767个字节。它尝试创建的主键是varchar(255)和@JoinColumn的组合,该组合超出了默认的列大小。您需要[更改数据库](http://stackoverflow.com/questions/1814532/1071-specified-key-was-too-long-max-key-length-is-767-bytes)或修改您的@提供长度的MapKeyColumn:`@MapKeyColumn(name =“ name”,length = 100)。 (2认同)

wci*_*iel 16

  @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>();
Run Code Online (Sandbox Code Playgroud)

这是关于如何设置控制列和表名称以及字段长度的映射的示例.

  • 获取类型应该是 *EAGER* (2认同)