将实体中的列表转换为数据库中的单个字符串列 [英] Convert list in entity to single string column in database

查看:105
本文介绍了将实体中的列表转换为数据库中的单个字符串列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有一个 VARCHAR 字段,这个字段的值是 val1,val2,val3

是否可以使用逗号作为分隔符将其设置为实体的 ArrayList< String> 属性?如果你使用JPA 2.1,那么你可以创建一个 AttributeConverter

  @Converter 
public class StringListConverter实现了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(,)));
}

}

你可以在你的转换器中使用

  @Column 
@Convert(converter = StringListConverter.class)
private List< String>串;

在JPA 2.1之前,您可以手动完成此操作:

  @Entity 
私有MyEntity {
...
私有字符串字符串;

公开列表< String> getStrings(){
返回Arrays.asList(strings.split(,));


public void setStrings(List< String> list){
strings = String.join(,,list);


我换行 Arrays.asList转换器中的 ArrayList 中的,因为结果存储在属性中,并且对该列表的任何更改都将被写回到数据库中 - 因此我需要一个可更改的列表(我不能添加任何内容到 Arrays.asList 的结果)。在 2.1之前的解决方案中,结果不与属性相关联,并且可变列表不会与属性同步。



查询一个包含这个属性中特定项目的实体,请参阅我的答案此处


I have a VARCHAR field in my database, and the value of this field is val1,val2,val3.

Is it possible to set this into an ArrayList<String> attribute of an entity using comma as split delimiter?

解决方案

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;

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);
  }
}

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆