Java JPA:在单个字段中存储整数列表
是否可以使用标准JPA 2在相应实体表的单个字段中存储整数列表Java JPA:在单个字段中存储整数列表,java,spring-boot,jpa-2.0,Java,Spring Boot,Jpa 2.0,是否可以使用标准JPA 2在相应实体表的单个字段中存储整数列表 @Entity @Table(name="tbl_myentities") public class MyEntity { @ElementaryCollection @Column(name="vals") // in table tbl_myentities private List<Integer> vals; @实体 @表(name=“tbl\U myentities”) 公共类MyEntity{ @元素集合
@Entity
@Table(name="tbl_myentities")
public class MyEntity {
@ElementaryCollection
@Column(name="vals") // in table tbl_myentities
private List<Integer> vals;
@实体
@表(name=“tbl\U myentities”)
公共类MyEntity{
@元素集合
@列(name=“vals”)//在表tbl\u myentities中
私人名单;
不可能在单个字段中存储多个值。将它们存储在单个字段中的原因是什么
一种方法是使用字符串类型的字段,将所有整数添加到逗号分隔的列表中,并在getter和setter中连接/分解:
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
控制映射需要一个单独的表来存储其中的值
@ElementCollection
private Collection<Integer> integers;
@ElementCollection
私有集合整数;
在上阅读有关元素集合的更多信息
这里有一个类似的问题,我认为这是不可能的。因为数据库表中不能有一列允许您存储整数列表 您可以使用字符串类型字段而不是整数列表-
@Column(name="vals") // in table tbl_myentities
private String vals;
在保存实体之前和读取实体之后,手动将整数列表转换为字符串并返回。也许@Lob适合您?(不管它意味着什么)
@Lob
ArrayList VAL;
(请注意,您的集合必须显式为ArrayList)您可以将所有VAL存储在字符串字段中,用逗号分隔,并更改相关的getter和setter,如下所示:
public List<Integer> getVals() {
List<Integer> lstVals = new ArrayList<Integer>();
int val = 0;
for(String field : this.vals.split(",")) {
try {
val = Integer.parseInt(field);
}
// If the String contains other thing that digits and commas
catch (NumberFormatException e) {
}
lstVals.add(val);
}
return lstVals;
}
public void setVals(List<Integer> vals) {
String newVals = "";
for(int i : vals) {
newVals.concat(String.valueOf(i));
}
this.vals = newVals;
}
public List getVals(){
List lstVals=new ArrayList();
int-val=0;
for(字符串字段:this.vals.split(“,”)){
试一试{
val=Integer.parseInt(字段);
}
//如果字符串包含其他数字和逗号
捕获(数字格式){
}
增加(val);
}
返回lst值;
}
公共无效设置值(列出VAL){
字符串newVals=“”;
用于(int i:VAL){
newVals.concat(String.valueOf(i));
}
this.vals=newVals;
}
您可以创建一个转换器,并将其与注释@converter一起使用
此转换器必须实现AttributeConverter,它是一个通用接口,有两个方法convertToDatabaseColumn和convertToEntityAttribute
它非常容易使用,您可以在这里检查:它说,“ElementCollection值总是存储在一个单独的表中。”我认为这不是OP想要的。@Wingie也是ArrayList的显式getter/setter吗?由此得到以下错误:
class=java.lang.ClassCastException,error=java.util.ArrayList不能转换为java.sql.Blob
不要认为此解决方案有效。
public List<Integer> getVals() {
List<Integer> lstVals = new ArrayList<Integer>();
int val = 0;
for(String field : this.vals.split(",")) {
try {
val = Integer.parseInt(field);
}
// If the String contains other thing that digits and commas
catch (NumberFormatException e) {
}
lstVals.add(val);
}
return lstVals;
}
public void setVals(List<Integer> vals) {
String newVals = "";
for(int i : vals) {
newVals.concat(String.valueOf(i));
}
this.vals = newVals;
}