有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JPA:在单个字段中存储整数列表

是否可以使用标准JPA 2在相应实体表的单个字段中存储整数列表

@Entity
@Table(name="tbl_myentities")
public class MyEntity {

@ElementaryCollection
@Column(name="vals") // in table tbl_myentities
private List<Integer> vals;

共 (5) 个答案

  1. # 1 楼答案

    也许@Lob适合你?(不管它意味着什么)

    @Lob
    ArrayList<String> vals;
    

    (请注意,集合必须显式为ArrayList)

  2. # 3 楼答案

    我认为那是不可能的。因为数据库表中不能有允许存储整数列表的列

    您可以使用字符串类型字段而不是整数列表-

    @Column(name="vals") // in table tbl_myentities
    private String vals;
    

    并在保存实体之前和读取实体之后,手动将整数列表转换为字符串并返回

  3. # 4 楼答案

    不可能在单个字段中存储多个值。将它们存储在单个字段中的原因是什么

    一种方法是使用字符串类型的字段,将所有整数添加到逗号分隔的列表中,并在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;
    

    阅读有关http://en.wikibooks.org/wiki/Java_Persistence/ElementCollection上元素集合的详细信息

    这里有类似的问题Does JPA @ElementCollection annotation always produce an one-to-many relationship?

  4. # 5 楼答案

    您可以将所有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;
    }