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

Mic*_*ael 16 java jpa-2.0 spring-boot

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

就像是:

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

   @ElementaryCollection
   @Column(name="vals") // in table tbl_myentities
   private List<Integer> vals;
Run Code Online (Sandbox Code Playgroud)

谢谢

MrK*_*ane 10

无法在单个字段中存储多个值.是什么原因将它们存储在一个字段中?

一种方法可以是使用String类型的字段,并在逗号分隔列表中添加所有整数,并在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
}
Run Code Online (Sandbox Code Playgroud)

使用@ElementCollection注释并@CollectionTable控制映射需要一个单独的表来存储值.

@ElementCollection
private Collection<Integer> integers;
Run Code Online (Sandbox Code Playgroud)

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

类似的问题JPA @ElementCollection注释是否总是产生一对多的关系?

  • 它说,“ElementCollection 值始终存储在单独的表中。” (2认同)