返回博主主页

JPA 自动处理数组字段

//    @ElementCollection
//    @CollectionTable(name = "specification_vote_task_reviewer", joinColumns = @JoinColumn(name = "vote_task_id"))
    @Convert(converter = IntegerListConverter.class)
    @Column(nullable = true, columnDefinition = "varchar(512) comment 'xxx'")
    private List<Integer> reviewerList;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.AttributeConverter;
public class IntegerListConverter implements AttributeConverter<List<Integer>, String> {
    private static final String DELIMITER = ",";


    @Override
    public String convertToDatabaseColumn(List<Integer> attribute) {
        if (CollectionUtils.isEmpty(attribute)) {
            return "";
        }
        final List<String> interStringValueList = attribute.stream().map(String::valueOf).collect(Collectors.toList());
        return String.join(DELIMITER, interStringValueList);
    }


    @Override
    public List<Integer> convertToEntityAttribute(String dbData) {
        if (StringUtils.isEmpty(dbData)) {
            return Collections.emptyList();
        }
        final List<String> interStringValueList = Arrays.asList(dbData.split(DELIMITER));
        return interStringValueList.stream().map(Integer::valueOf).collect(Collectors.toList());
    }
}

image

posted @ 2024-12-10 21:45  懒惰的星期六  阅读(3)  评论(0编辑  收藏  举报

Welcome to here

主页