@Override
@Mappings(
{
@Mapping(target = "temperature", source = "pac.temperature"),
@Mapping(target = "containerId", ignore=true),
}
)
TargetABC toDto(Source source);
@AfterMapping
default void inRange(Source source, @MappingTarget TargerABC target) {
var temperature = source.getPac.getTemperature();
var range = source.getRange();
target.setContainerId(
range.calculate(temperature)
);
}
at the moment I have a solution using @AfterMapping
, but I want to get rid of this approach in favor of qualifiedByName
and do the mapping in the field itself by adding a method with the @Named
annotation, is it possible that such a method will take two values? Maybe there is another better solution?
CodePudding user response:
You can define custom method which will accept Source
as parameter and will make required computations. Call this method from @Mapping
using expression= "java(<method_name>)"
.
@Mapping(target = "containerId",expression = "java(calculateContainerId(source))")
TargetABC toDto(Source source);
default String calculateContainerId(Source source) {
var temperature = source.getPac.getTemperature();
var range = source.getRange();
return range.calculate(temperature);
}
CodePudding user response:
The simplest solution is defining a default method for mapping source
to containerId
, which would MapStruct recognize and use if you define source
as the source used for mapping, as shown below:
@Mapping(target = "temperature", source = "pac.temperature")
@Mapping(target = "containerId", source = "source")
TargerABC toDto(Source source);
default Integer calculateContainerIdFromSource(Source source) {
var temperature = source.getPac().getTemperature();
var range = source.getRange();
return range.calculate(temperature);
}