将实体中的列表转换为数据库中的单个字符串列 [英] Convert list in entity to single string column in database
问题描述
我的数据库中有一个 VARCHAR
字段,该字段的值为 val1,val2,val3
.
I have a VARCHAR
field in my database, and the value of this field is val1,val2,val3
.
是否可以将其设置为使用逗号作为拆分分隔符的实体的 ArrayList
属性?
Is it possible to set this into an ArrayList<String>
attribute of an entity using comma as split delimiter?
推荐答案
如果你使用JPA 2.1,那么你可以创建一个AttributeConverter
:
If you use JPA 2.1, then you can create an AttributeConverter
:
@Converter
public class StringListConverter implements AttributeConverter<List<String>, String> {
@Override
public String convertToDatabaseColumn(List<String> list) {
// Java 8
return String.join(",", list);
// Guava
return Joiner.on(',').join(list);
}
@Override
public List<String> convertToEntityAttribute(String joined) {
return new ArrayList<>(Arrays.asList(joined.split(",")));
}
}
您可以在您的实体中使用此转换器:
You can use this converter in your entity:
@Column
@Convert(converter = StringListConverter.class)
private List<String> strings;
在 JPA 2.1 之前,您可以手动执行此操作:
For before JPA 2.1 you could do this by hand:
@Entity
private MyEntity {
...
private String strings;
public List<String> getStrings() {
return Arrays.asList(strings.split(","));
}
public void setStrings(List<String> list) {
strings = String.join(",", list);
}
}
我将 Arrays.asList
包装在转换器中的 ArrayList
中,因为结果存储在属性中,对该列表的任何更改都将写回数据库- 因此我需要一个可更改的列表(我不能在 Arrays.asList
的结果中添加任何内容).在 2.1 之前 解决方案中,结果与属性无关,并且可变列表不会与属性同步.
I wrap Arrays.asList
in an ArrayList
in the converter, because the result is stored in the attribute and any change to that list will be written back to the database - thus I need a changeable list (I can't add anything to the result of Arrays.asList
). In the before 2.1 solution the result is not connected with the attribute and a changeable list would not be synchronized with the attribute.
要查询在此类属性中包含特定项目的实体,请参阅我的回答 这里
To query for an entity that contains a specific item in such an attribute, see my answer here
这篇关于将实体中的列表转换为数据库中的单个字符串列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!