首頁  >  問答  >  主體

使用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粉317679342297 天前453

全部回覆(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
  • 取消回覆