Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Additional parameter in mapstruct mapper

Tags:

java

mapstruct

I have Car:

  • id
  • brand
  • model
  • owner

And CarDTO:

  • id
  • brand
  • model

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);
}
like image 815
TheFastestTurtle Avatar asked Feb 12 '26 04:02

TheFastestTurtle


1 Answers

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);
}
like image 88
Toni Avatar answered Feb 13 '26 18:02

Toni