Background
We are currently implementing an application using hexagonal architecture. Our REST API DTOs are mapped to our entities via MapStruct. This works fine. (Though, it would be much nicer if MapStruct would have support for hierarchical structures.)
Problem
However, we are facing a problem which is best described by the following example:
Consider you have an entity Person
that stores the date of birth. Now, this
entity has a method which might be called int calculateAge()
.
The REST API's PersonDto
will get an attribute int age
.
Now, we want MapStruct to generate this mapping for us. Our approach was to try to configure @Mapping(target = "age", ...)
to use the int calculateAge()
method as source, but we did not succeed.
Believing this might be a straightforward application of MapStruct, we were quite disappointed to not come up with a clean solution after searching on this topic for hours.
Solutions
We found two solution approaches that work, but are (in our opinion) not really maintainable:
- Use
@Mapping(expression = "java(...)")
- Use
@AfterMapping
to post process the constructed DTO and implement the required mappings in the annotated method
Question
Is there a cleaner way to achieve our goal, something which might look like this @Mapping(sourceMethod = "calculateAge", target = "age)
?
question from:
https://stackoverflow.com/questions/65903019/use-entity-method-as-mapstruct-source 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…