java JPA:在单个字段中存储整数列表
是否可以使用标准JPA 2在相应实体表的单个字段中存储整数列表
@Entity
@Table(name="tbl_myentities")
public class MyEntity {
@ElementaryCollection
@Column(name="vals") // in table tbl_myentities
private List<Integer> vals;
你可以在下面搜索框中键入要查询的问题!
是否可以使用标准JPA 2在相应实体表的单个字段中存储整数列表
@Entity
@Table(name="tbl_myentities")
public class MyEntity {
@ElementaryCollection
@Column(name="vals") // in table tbl_myentities
private List<Integer> vals;
# 1 楼答案
也许@Lob适合你?(不管它意味着什么)
(请注意,集合必须显式为ArrayList)
# 2 楼答案
您可以创建一个转换器,并将其与注释@converter一起使用
此转换器必须实现AttributeConverter,它是一个通用接口,有两个方法convertToDatabaseColumn和convertToEntityAttribute
它很容易使用,您可以在这里查看:jpa independent custom type mapping / javax.persistence.x alternative to org.hibernate.annotations.Type and org.hibernate.annotations.TypeDef
# 3 楼答案
我认为那是不可能的。因为数据库表中不能有允许存储整数列表的列
您可以使用字符串类型字段而不是整数列表-
并在保存实体之前和读取实体之后,手动将整数列表转换为字符串并返回
# 4 楼答案
不可能在单个字段中存储多个值。将它们存储在单个字段中的原因是什么
一种方法是使用字符串类型的字段,将所有整数添加到逗号分隔的列表中,并在getter和setter中连接/分解:
使用
@ElementCollection
注释和@CollectionTable
来控制映射需要一个单独的表来存储其中的值阅读有关http://en.wikibooks.org/wiki/Java_Persistence/ElementCollection上元素集合的详细信息
这里有类似的问题Does JPA @ElementCollection annotation always produce an one-to-many relationship?
# 5 楼答案
您可以将所有VAL存储在字符串字段中,用逗号分隔,并更改相关的getter和setter,如下所示: