JPA:在单个字段中存储整数列表 [英] JPA: Store a list of integers in a single field
问题描述
是否可以在标准JPA 2的相应实体表的单个字段中存储整数列表?
Is it possible to store a list of integers in a single field of the respective entity table with standard JPA 2?
类似于:
@Entity
@Table(name="tbl_myentities")
public class MyEntity {
@ElementaryCollection
@Column(name="vals") // in table tbl_myentities
private List<Integer> vals;
谢谢
推荐答案
无法在单个字段中存储多个值。是什么原因将它们存储在一个字段中?
It is not possible to store multiple values in a single field. Whats the reason behind storing them in a single field?
一种方法可能是使用String类型的字段并在逗号分隔列表中添加所有整数并加入/在getter和setter中爆炸:
A way could be to use a field of type String and add all integers there in a comma separated list and join/explode in getters and setters:
private String vals;
public setVals(int vals[])
{
// this.vals = Iterate vals[] and create a comma separated string
}
public int[] getVals()
{
// vals.split(",") to get a list of Strings, then typecast/parse them to ints before returning
}
使用 @ElementCollection
注释和 @CollectionTable
控制映射需要一个单独的表来存储值。
Using the @ElementCollection
annotation and @CollectionTable
to control the mappings requires a separate table to store the values in.
@ElementCollection
private Collection<Integer> integers;
详细了解 http://en.wikibooks.org/wiki/Java_Persistence/ElementCollection
相似的问题这里 JPA @ElementCollection注释是否总是生成一个注释多对多关系?
这篇关于JPA:在单个字段中存储整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!