Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse mapping with custom mapper with mapstruct

Tags:

java

mapstruct

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?

like image 947
Don Hosek Avatar asked Oct 24 '25 18:10

Don Hosek


1 Answers

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.

like image 139
Filip Avatar answered Oct 26 '25 07:10

Filip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!