Use case
We have this model:
class Model {
List<Item> items;
UUID modelId;
}
class Item {
UUID itemId;
String name;
}
class ItemDTO {
UUID itemId;
String name;
UUID modelId;
}
Now we want map an instance of Model to List of ItemDTO. Se want to map the modelId field to each ItemDTO. We are not able to do it simply with Mapstruct:
@Mapping(source="items", target=".")
@Mapping(source="modelId", target=".")
List<ItemDTO> toDto(Model model)
This does not work and it is clear why. So we rewrite it like this:
default List<ItemDTO> toDto(Model model) {
return toDto(model.getItems(), model.getModelId());
}
List<ItemDTO> toDto(List<Item> items, @Context UUID modelId);
@Mapping(source="modelId", target="modelId")
ItemDTO toDto(Item item, @Context UUID modelId);
But it does not work because @Context parameter cannot be used as a source. And it throws:
No property named "modelId" exists in source parameter(s). Did you mean "itemId"?
So it would be really useful to allow to use @Context parameters as a source. Mainly if you want to use the same value for all iterable.
Generated Code
No response
Possible workarounds
So we use one of these workarounds:
expression
@Mapping(target="modelId", expression = "java(modelId)")
ItemDTO toDto(Item item, @Context UUID modelId);
@AfterMapping
@AfterMapping
default void toDto(@MappingTarget ItemDTO target, Item item, @Context UUID modelId) {
target.setModelId(modelId);
}
MapStruct Version
MapStruct 1.6.0
Use case
We have this model:
Now we want map an instance of
ModeltoListofItemDTO. Se want to map themodelIdfield to eachItemDTO. We are not able to do it simply with Mapstruct:This does not work and it is clear why. So we rewrite it like this:
But it does not work because
@Contextparameter cannot be used as a source. And it throws:So it would be really useful to allow to use
@Contextparameters as a source. Mainly if you want to use the same value for all iterable.Generated Code
No response
Possible workarounds
So we use one of these workarounds:
expression
@AfterMapping
MapStruct Version
MapStruct 1.6.0