存储 Map<String,String>使用 JPA [英] Storing a Map&lt;String,String&gt; using JPA

查看:45
本文介绍了存储 Map<String,String>使用 JPA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>();
    // ....
}

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

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));

推荐答案

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

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

}

另见(在 JPA 2.0 规范中)

  • 2.6 - 可嵌入类和基本类型的集合
  • 2.7 地图集合
  • 10.1.11 - ElementCollection 注释
  • 11.1.29 MapKeyColumn 注释
  • 这篇关于存储 Map<String,String>使用 JPA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆