我该如何映射在JPA地图,而使用Hibernate的班?
public Map<String, String[]> parameters = new HashMap<String, String[]>();
提前致谢。
我该如何映射在JPA地图,而使用Hibernate的班?
public Map<String, String[]> parameters = new HashMap<String, String[]>();
提前致谢。
示例实现:
@Entity
@Table(name = "MAP") //optional
public class Parameters {
@Id
@Column(name = "\"KEY\"") //optional
private String id;
@ElementCollection
@CollectionTable( //optional
name = "MAP_VALUES",
joinColumns = { @JoinColumn(name="MAP_KEY") }
)
private Collection<String> collection;
public Parameters() { }
public Parameters(String key, Collection<String> values) {
this.id = key;
this.collection = values;
}
public Collection<String> values() {
return collection;
}
// ...
}
实体实例可以被插入到数据库中,如下所示:
em.persist(new Parameters("first", Arrays.asList("a", "b", "c")));
em.persist(new Parameters("second", Arrays.asList("d", "e", "f")));
...
这将在数据库中的两个表:
MAP MAP_VALUES
KEY MAP_KEY COLLECTION
------ ------- ----------
first first a
second first b
second c
second d
MAP_KEY
列MAP_VALUES
表的外键,指的是MAP
表。
内容可以检索如下:
Parameters entry = em.find(Parameters.class, "second");
List<String> values = entry.values();
...
要么
String query = "SELECT p FROM Parameters p";
List<Parameters> entries = em.createQuery(query, Parameters.class)
.getResultList();
List<String> values = entry.values();
...