Issue
MyOM
and MyEntity
objects have an id as a field
The function map()
works. If I set the id parameter, then my MyEntity in map()
receives this parameter.
I want to do the same thing with mapDTOs()
. When it receives a value for id it must be propagated to all calls of map()
during the loop.
How can I do this?
@Mapping(target = "id", expression = "java(id)")
MyEntity map(MyOM om, String id);
@Mapping(target = ??, expression = ??)
List<MyEntity> mapDTOs(List<MyOM> dtos, String id);
Solution
The additional parameter should be annotated with @Context
if meant to be passed to other mapping methods. The annotation was introduced in the 1.2 version, more info can be found in MapStruct documentation.
Your method should be declared without any @Mapping
annotation as:
List<MyEntity> mapDTOs(List<MyOM> dtos, @Context String id);;
Since @Context
parameters are not meant to be used as source parameters, a proxy method should be added to point MapStruct to the right single object mapping method to make it work.
default MyEntity mapContext(MyOM om, @Context String id) {
return map(om, id);
}
In case there is no proxy method, MapStruct would generate a new method for mapping a single object without mapping id
because the existing one doesn't contain a second parameter marked as @Context
.
This solution is simple but perhaps doesn't use @Context
in the right way, for a better understanding of @Context
usage check Filip's answer.
Answered By - birca123
Answer Checked By - Candace Johnson (JavaFixing Volunteer)