Retrieve JSON array or JSON object using JPA projection and DTO interface
P粉317679342
P粉317679342 2023-12-27 23:37:14
0
1
418

I have a DTO interface that uses joins to get data from different tables. I created a DTO interface with abstract getter methods like this.

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();
}

In this interface, my getFreelanceInvoiceId(); method uses mysql's json_arrayagg function to return a JSON array. I changed the data type to String, String[] and Arraylist but it returns something like

in my response
"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"]"

Is there any way to return only an array that does not contain backslashes?

P粉317679342
P粉317679342

reply all(1)
P粉463291248

You can use @Converter in JPA (also implemented by 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);
    }
}

And reference it in the pojo class as shown below

@Column(name="freeLanceInvoiceId")
@Convert(converter = List2StringConveter.class)
private List<String> tags=new ArrayList<>();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!