Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapstruct: passing one additional parameter in order to propagate it

Tags:

java

mapstruct

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);
like image 355
jeangr Avatar asked Oct 20 '25 11:10

jeangr


1 Answers

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.

like image 93
Toni Avatar answered Oct 23 '25 01:10

Toni



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!