使用JPA投影和DTO介面檢索JSON數組或JSON對象
P粉317679342
P粉317679342 2023-12-27 23:37:14
0
1
452

我有一個 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粉317679342
P粉317679342

全部回覆(1)
P粉463291248

您可以使用 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<>();
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!