首页  >  问答  >  正文

使用JPA投影和DTO接口检索JSON数组或JSON对象

我有一个 DTO 接口,它使用联接从不同的表中获取数据。我用类似这样的抽象 getter 方法创建了一个 DTO 接口。

public interface HRJobsDTO {

    String getEditorName();

    String getEditorId();

    String getBillingMonth();

    Integer getEditorWordCount();

    Integer getJobCount();

    Integer getEmployeeGrade();

    Float getGrossPayableAmount();

    Float getJobBillingRate();

    Float getTaxDeduction();

    Float getTaxDeductionAmount();

    Float getNetPayableAmount();

    String getInvoiceStatus();

    String getFreelanceInvoiceId();
}

在此界面中我的 getFreelanceInvoiceId();方法使用 mysql 的 json_arrayagg 函数返回一个 JSON 数组。我将数据类型更改为 String、String[] 和 Arraylist,但它在我的响应中返回类似的内容

"freelanceInvoiceId": "["4af9e342-065b-4594-9f4f-a408d5db9819/2022121-95540", "4af9e342-065b-4594-9f4f-a408d5db9819/2022121-95540", "4af9e342-065b-4594-9f4f-a408d5db9819/20221215-53817", "4af9e342-065b-4594-9f4f-a408d5db9819/20221215-53817", "4af9e342-065b-4594-9f4f-a408d5db9819/20221215-53817"]"

有什么方法可以只返回不包含反斜杠的数组吗?

P粉317679342P粉317679342296 天前450

全部回复(1)我来回复

  • P粉463291248

    P粉4632912482023-12-28 10:29:22

    您可以使用 JPA 中的@Converter(也由 hibernate 实现)

    @Converter
    public class List2StringConveter implements AttributeConverter<List<String>, String> {
    
        @Override
        public String convertToDatabaseColumn(List<String> attribute) {
            if (attribute == null || attribute.isEmpty()) {
                return "";
            }
            return StringUtils.join(attribute, ",");
        }
    
        @Override
        public List<String> convertToEntityAttribute(String dbData) {
            if (dbData == null || dbData.trim().length() == 0) {
                return new ArrayList<String>();
            }
    
            String[] data = dbData.split(",");
            return Arrays.asList(data);
        }
    }

    并在 pojo 类中引用它,如下所示

    @Column(name="freeLanceInvoiceId")
    @Convert(converter = List2StringConveter.class)
    private List<String> tags=new ArrayList<>();

    回复
    0
  • 取消回复