Home > Back-end >  How to use mapstruct with a source that has two parameters?
How to use mapstruct with a source that has two parameters?

Time:02-01

It seems the mapstruct can work with source with only one parameter. If do set "source = {"id","name"} " when I will have error. How solve it?

 @Mapping(source = {"id","name"}, target = "person", qualifiedByName = "toPerson")
 public MainData toEntity(InfoDTO dto);
 
    @Named("toPerson")
    public Person toPerson(Long id, String name) {
        //some to do
    }

My entities:

MyData{
Person person;
}

InfoDTO{
Long id;
String name;
}

CodePudding user response:

Could be done in this way:

@Mapper(componentModel = "spring")
public interface PersonMapper {

    @Mapping(expression = "java(toPerson(dto))", target = "person")
    MyData toEntity(InfoDto dto);

    default Person toPerson(InfoDto dto) {
        return new Person(dto.getId(),dto.getName());
    }

}
  •  Tags:  
  • Related