Reputation: 149
I have Car:
And CarDTO:
In my service class I'm passing additional parameter "owner" and I need to convert the list.
Is it possible to add "owner" to Mapper?
If yes then I suppose it should be something similar to this (not working).
@Mapper
public interface CarMapper {
@Mapping(target = "owner", source = "owner")
List<Car> mapCars(List<CarDTO> cars, String owner);
}
Upvotes: 13
Views: 15590
Reputation: 7744
I didnt even have to use context. I could simply pass the additional parameter and the mapper recognises it in the build.
NotMORV2Entity toNotMorV2Entity(ReEntity reEntity, int glAccountTypeId);
Please also see this to understand more.
Upvotes: 1
Reputation: 5115
As described in the answer, you can use @Context
.
Firstly, add a single object mapping method:
@Maping(target = "owner", source = "owner")
Car mapCar(CarDTO car, String owner);
Then define a method for mapping a list of objects with @Context
:
List<Car> mapCars(List<CarDTO> cars, @Context String owner);
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.
In the end, add the proxy method:
default Car mapContext(CarDTO car, @Context String owner) {
return mapCar(car, owner);
}
Upvotes: 12
Reputation: 1763
Yes it is possible. You could try the @Context
annotation before "owner"
I would suggest something like this:
@Mapper
public interface CarMapper {
@Maping(target = "owner", source = "owner")
Car mapCar(CarDTO car, @Context String owner);
@Maping(target = "owner", source = "owner")
List<Car> mapAllCars(List<CarDTO> cars, @Context String owner);
@AfterMapping
default void afterMapping(@MappingTarget Car target, @Context String owner) {
target.setOwner(owner);
}
there are multiple ways to approache your problem. You could also have a look at Passing additional parameters to MapStruct mapper
Upvotes: 0