How mapping to List<> with mapstruct

2019-08-21 01:48发布

问题:

Hi i need mappig variables to request. How can i mapp into List. My request looks like.

public class Request {
    private String Id;
    private List<Data> applicationData;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Data {
        private String data1;
        private String data2;
        private String data3;
    }
}

and my mapper

@Mapper(componentModel = "spring")
public abstract class RequestMapper {
    @Mapping(target = "Id", source = "data.Id")
    @Mapping(target = "data.???.data1", source = "data.data1")
    @Mapping(target = "data.???.data2", source = "data.data2")
    @Mapping(target = "applicationData.???.data3", source = "data.data3")
    public abstract Request map(Data variables);
}

回答1:

From what I understand you want to map your values into a singleton list. You can achieve that by providing 2 new methods in your mapper.

You mapper would look like:

@Mapper(componentModel = "spring")
public abstract class RequestMapper {
    @Mapping(target = "Id", source = "Id")
    @Mapping(target = "data", source = "variables")        
    public abstract Request map(Data variables);

    protected List<Data> mapToList(Data variables) {
        return variables == null ? null : mapToApplication(variables);
    }

    //Add mappings if they are needed
    protected abstract ApplicationData mapToApplication(Data variables);
}