我想知道是否可以使用注释来使用 JPA2 将 attributes
映射保留在以下类中
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));
最佳答案
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 map 集合
- 10.1.11 - ElementCollection 注释
- 11.1.29 MapKeyColumn 注解
关于java - 使用 JPA 存储 Map<String,String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3393649/