Maison  >  Questions et réponses  >  le corps du texte

Récupérer un tableau JSON ou un objet JSON à l'aide de la projection JPA et de l'interface DTO

J'ai une interface DTO qui utilise des jointures pour obtenir des données de différentes tables. J'ai créé une interface DTO avec des méthodes getter abstraites comme celle-ci.

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

Dans cette interface, ma méthode getFreelanceInvoiceId(); utilise la fonction json_arrayagg de MySQL pour renvoyer un tableau JSON. J'ai changé le type de données en String, String[] et Arraylist mais cela renvoie quelque chose comme ceci dans ma réponse

"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"]"

Existe-t-il un moyen de renvoyer uniquement des tableaux sans barres obliques inverses ?

P粉317679342P粉317679342296 Il y a quelques jours448

répondre à tous(1)je répondrai

  • P粉463291248

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

    Vous pouvez utiliser @Converter dans JPA (également implémenté par 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);
        }
    }

    et référencez-le dans la classe pojo comme indiqué ci-dessous

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

    répondre
    0
  • Annulerrépondre