JPA:将值列表保存为逗号分隔值

Him*_*dav 9 java hibernate jpa

我收到一个简单的 JSON 请求值列表,我想将其保存为逗号分隔值。尝试使用以下,但没有奏效。

@Column(nullable = true)
@GeneratedValue(strategy = GenerationType.AUTO)
private ArrayList<String> services = new ArrayList<String>() ;
Run Code Online (Sandbox Code Playgroud)

@Column(nullable = true)
@ElementCollection(targetClass = String.class)
private List<String> services = new ArrayList<String>() ;
Run Code Online (Sandbox Code Playgroud)

@ElementCollection抛出异常说table services does not exist

Túl*_*tro 10

@ElementCollection 需要一个表来存储多行值,

所以你可以定义为一个字符串列并在 getter 和 setter 中加入/爆炸,就像这样

private String services;

public setServices(String services[]) //Can be Array or List
{
     // this.services = Iterate services[] and create a comma separated string or Use ArrayUtils
}

public String[] getServices() //Can be Array or List
{
    // services.split(",") to get a list of Strings, then typecast/parse them to Strings before returning or use Arrays.asList(arguments.split(","));
}
Run Code Online (Sandbox Code Playgroud)


ped*_*rro 5

正如其他人在评论中提到的,AttributeConverter效果很好。这个使用 Jackson 序列化为 JSON 数组。我推荐 JSON,因为它可以干净地处理分隔符转义、空值、引号等:

@Converter
public class StringListAttributeConverter implements AttributeConverter<List<String>, String> {

    private static final TypeReference<List<String>> TypeRef = new TypeReference<List<String>>(){};

    @Override
    public String convertToDatabaseColumn (List<String> attribute) {
        if (attribute == null) {
            return null;
        }
        try {
            return ObjectMapperFactory.getInstance().writeValueAsString(attribute);
        }
        catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }

    @Override
    public List<String> convertToEntityAttribute (String dbData) {
        if (dbData == null) {
            return null;
        }
        try {
            return ObjectMapperFactory.getInstance().readValue(dbData, TypeRef);
        }
        catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经使用过这个类,它在大多数情况下运行良好。我发现的一个警告是,使用此转换器可能会混淆一些 JPA 条件查询,因为它需要实体上的类型 List,但在 db 中找到一个 String。


Mar*_*cel 5

一个更简单的变体对我来说很有效,不是杰克逊,而是修剪字符串:

public class CsvTrimmedStringsConverter implements AttributeConverter<List<String>, String> {
  @Override
  public String convertToDatabaseColumn(List<String> attribute) {
    return attribute == null
        ? null
        : attribute.stream().map(String::trim).collect(Collectors.joining(","));
  }

  @Override
  public List<String> convertToEntityAttribute(String dbData) {
    return dbData == null
        ? null
        : Arrays.stream(dbData.split(",")).map(String::trim).collect(Collectors.toList());
  }
}
Run Code Online (Sandbox Code Playgroud)