This is my example.
public class Company {
....
private String companyName;
....
}
public class Employee {
....
private String name;
....
}
public class EmployeeDto {
....
private String name;
private String companyName;
....
}
@Mapper(componentModel = "spring")
public interface EmployeeDtoMapper {
@Mapping(target = "name", source = "source1.name")
@Mapping(target = "companyName", source = "source2.companyName")
EmployeeDto toDto(Employee source1, Company source2);
List<EmployeeDto> toDtos(List<Employee> sources, @Context Company source2);
}
I want that the method toDtos use toDto to map Employee to EmployeeDto but mapstruct generate a employeeDtoToEmployeeDto method. How can I fix it ?
thanks
Mapstruct only allows for selecting submappings based on 1 source and 1 target. Hence the @Context annotation. This will effectively ignore that parameter, only handed it down to submapping..
But.. you can tackle your problem like this..
@Mapper(componentModel = "spring")
public interface EmployeeDtoMapper {
@Mapping(target = "name", source = "source1.name")
EmployeeDto toDto(Employee source1, @Context Company source2);
@AfterMapping
default afterToDto(@MappingTarget EmployeeDto target, @Context Company source2) {
target.setCompanyName( source2.getCompanyName();
}
List<EmployeeDto> toDtos(List<Employee> sources, @Context Company source2);
}
Note if you have multiple parameters in mapping source2, and you like to use MapStruct for that as well, you can define a new interface method mapping EmployDTO toDo(Company source)
and call that from your default method.