112

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

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

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

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

2 回答 2

215

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

}

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

  • 2.6 - 可嵌入类和基本类型的集合
  • 2.7 地图集合
  • 10.1.11 - ElementCollection 注解
  • 11.1.29 MapKeyColumn注解
于 2010-08-03T05:21:41.227 回答
23
  @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>();

这是一个关于如何设置一个可以控制列名和表名以及字段长度的地图的示例。

于 2014-08-25T13:16:54.617 回答