search

Home  >  Q&A  >  body text

Retrieve JSON array or JSON object using JPA projection and DTO interface

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粉317679342P粉317679342341 days ago494

reply all(1)I'll reply

  • P粉463291248

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

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

    reply
    0
  • Cancelreply