Inverse mapping with custom mapper with mapstruct

Don Hosek :

I have a mapping defined as

@Mapping(source = "diagnoses", target = "diagnosisCode", qualifiedByName = "mapDiagnosisCodeAsList")

Where mapDiagnosisCodeAsList is defined as follows:

@Named("mapDiagnosisCodeAsList")
default List<String> retrieveDiagnosisCodeAsList(List<Diagnosis> aList) {
    if (CollectionUtils.isEmpty(aList)) {
        return new ArrayList<>();
    }
    return aList.stream().map(Diagnosis::getDiagnosisCode).collect(Collectors.toList());
}

Inverse mappings are handled using @InheritInverseConfiguration. How do I specify a custom mapping for the inverse mapping?

Filip :

In order for the inverse mapping to work you'll need to provide the inverse method as well.

@Named("mapDiagnosisCodeAsList")
default List<Diagnosis> retrieveDiagnosisCodeAsList(List<String> aList) {
    if (CollectionUtils.isEmpty(aList)) {
        return new ArrayList<>();
    }
    return aList.stream().map(Diagnosis::new).collect(Collectors.toList());
}

One other side note. I think that you don't really need the complexity of qualifiers to make this work. If you have only one Diagnosis to String and reverse you can do it without qualifiers (even without the list).

Your @Mapping will stay the same without qualifiedByName and you need to provided mapping from Diagnosis to String and reverse.

default String diagnosisToString(Diagnosis diagnosis) {
    return diagnosis == null ? null : diagnosis.getDiagnosisCode();
}

default Diagnosis stringToDiagnosis(String diagnosisCode) {
    return diagnosis == null ? null : new Diagnosis(diagnosisCode);
}

The creation of the collection would be taken care by MapStruct. Also I assume that Diagnosis has a constructor that takes the code.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=422845&siteId=1