【问题标题】:mapstruct can not map property list of model to list of Stringmapstruct 无法将模型的属性列表映射到字符串列表
【发布时间】:2020-07-16 19:17:37
【问题描述】:

如何将差异模型列表字符串映射到下面的代码列表模型;

我的TaskList.class

@Getter
@Setter
private List<TaskGroupList> groupIds;

我的 TaskResponse.class

@Getter
@Setter
private List<String> groupIds;

我的 TaskGroupList 类

@Getter
@Setter
private String ownerId;

我的TaskListMapper.class

 public abstract List<TaskResponse> toAllTaskListResponse(List<TaskList> taskList);

【问题讨论】:

  • 发布了新答案

标签: java spring spring-boot spring-mvc jdbc


【解决方案1】:

对于映射到列表,我认为您需要使用 IterableMapping 注释。请参考以下链接-

https://mapstruct.org/documentation/stable/reference/html/#implicit-type-conversions

它有一个列表到列表转换的例子

@Mapper
public interface CarMapper {
  @IterableMapping(numberFormat = "$#.00")
  List<String> prices(List<Integer> prices);
}

因此,在您的场景中,您可以使用注释。此外,由于存在列表对象列表,因此需要嵌套迭代,如下所示 -

@IterableMapping(qualifiedBy = IterableMapping.class)
List<TaskResponse> toAllTaskListResponse(List<TaskList> taskList);

@IterableMapping(qualifiedByName = "taskGroup")
List<String> map(List<TaskGroupList> task);

@Named("taskGroup")
default String map(TaskGroupList t) {
    return t.getOwnerId();
}

【讨论】:

  • 感谢您的回答,当我使用该注释时,我有一个错误说; 'nullValueMappingStrategy', 'dategormat, 'qualifiedBy'' 和 'elementtargetType' 在@IterableMapping 中未定义至少定义其中之一'
  • 我通过邮寄方式更新了。错误中提到的需要其中一种策略
  • 非常感谢,我认为它会在我有@AfterMapping 注释的基础上起作用,让我出错。最好的方法是什么?
  • 能贴出相关代码吗?你得到什么错误?
  • 如果这回答了您的问题,请将其标记为答案。
【解决方案2】:
@Mapper(componentModel = "spring")
public interface CarListMapper {

    @Mapping(source = "groupIds",target = "groupIds",qualifiedByName = "toGroupId")
    TaskResponse toTaskResponse(TaskList taskList);

    List<TaskResponse> fromAllTaskList(List<TaskList> carDtoList);

    @Named("toGroupId")
    static List<String> toGroupId(List<TaskGroupList> groupIds){
        return groupIds.stream()
                .map(taskGroupList -> taskGroupList.getOwnerId()).collect(Collectors.toList());
    }
}

它对我有用

【讨论】:

  • 非常感谢您的回答。我很快就会使用这种方法:)
猜你喜欢
  • 1970-01-01
  • 2020-10-12
  • 2018-02-11
  • 1970-01-01
  • 2019-12-06
  • 2019-08-24
  • 2016-11-24
  • 2018-08-06
  • 1970-01-01
相关资源
最近更新 更多