Java 使用 JPA 存储 Map<String,String>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3393649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Storing a Map<String,String> using JPA
提问by corydoras
I am wondering if it is possible using annotations to persist the attributes
map in the following class using JPA2
我想知道是否可以使用注释将attributes
地图保存在使用 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:
由于我们已经有一个预先存在的生产数据库,因此理想情况下, 的值attributes
可以映射到以下现有表:
create table example_attributes {
example_id bigint,
name varchar(100),
value varchar(100));
采纳答案by Pascal Thivent
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:
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
}
See also (in the JPA 2.0 specification)
另请参阅(在 JPA 2.0 规范中)
- 2.6 - Collections of Embeddable Classes and Basic Types
- 2.7 Map Collections
- 10.1.11 - ElementCollection Annotation
- 11.1.29 MapKeyColumn Annotation
- 2.6 - 可嵌入类和基本类型的集合
- 2.7 地图集合
- 10.1.11 - ElementCollection 注释
- 11.1.29 MapKeyColumn 注解
回答by wciesiel
@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.
这是一个关于如何设置映射以控制列和表名称以及字段长度的示例。