0
votes

I have a mapping like this:

@Mappings({ 
    @Mapping(target = "....", source = "..."),
    @Mapping(target = "....", source = "..."),
    @Mapping(target = "server", source = "server") // Added for clarity
})
MyDTOClass mapMyEntity(MyEntityClass myEntityClass, Server server);
List<MyDTOClass> mapMyEntity(List<MyEntityClass> myEntityClass, Server server);

When I retrieve the data from database, I get a list of entities. I need to map the same Server object instance to all my DTO instances in the list.

MapStruct is expecting a List<Server> which is kind of redundant in this Use Case.

This is the pseudo-code of what I want:

Server server = ....;
List<MyDTOClass> myDTOClassList = new ArrayList<MyDTOClass>();
for(MyEntityClass myEntityClass:List<MyEntityClass>)
{
    MyDTOClass myDTOClass = new myDTOClass();
    //My standard mappings
    myDTOClass.setXXX(myEntityClass.getXXX());
    ...
    ...
    //My special mapping applicable for all objects in list
    myDTOClass.setServer(server);
    myDTOClassList.add(myDTOClass);
}

How can this be achieved?

1
Your question is not really clear. What exactly are you trying to map? Where is the List<Server> coming from? - Filip
My basic mapping is MyDTOClass mapMyEntity which I want to extend into a collection. But attach the same server object to all instances of the list. I added pseudo-code. Hope it's clear now. - user1880957

1 Answers

2
votes

You can achieve this by using the new @Context from 1.2. and @AfterMapping

@Mapper
public interface MyMapper {


    MyDTOClass mapMyEntity(MyEntityClass myEntityClass, @Context Server server);

    List<MyDTOClass> mapMyEntity(List<MyEntityClass> myEntityClass, @Context Server server);

    @AfterMapping
    default void afterMapping(@MappingTarget MyDTOClass target, @Context Server server) {
        target.setServer(server);
    }
}