MapStruct实现List<Long>转List<RelationDTO>的编码方案咨询
解决方案
你需要先定义单个business2Id转RelationDTO的转换规则,MapStruct会自动迭代调用该方法生成目标列表,修改后的转换接口代码如下:
@Mapper(componentModel = "spring") public interface RelationConverter { // 定义单个元素的转换规则 @Mapping(source = "business2Id", target = "business2Id") @Mapping(source = "business1Id", target = "business1Id") @Mapping(source = "createUser", target = "createUser") @Mapping(source = "createTime", target = "createTime") RelationDTO convertSingle(Long business2Id, Long business1Id, String createUser, LocalDateTime createTime); // 列表转换方法无需额外配置,MapStruct会自动循环调用上述单个转换方法 List<RelationDTO> convertTo(List<Long> business2IdList, Long business1Id, String createUser, LocalDateTime createTime); }
实现说明
MapStruct处理集合转换时,会自动查找集合元素类型对应的单个转换方法,将列表中的每个元素作为第一个参数传入单个转换方法,剩余的公共参数(business1Id、createUser、createTime)会原样透传给每次调用的单个转换方法,最终组装成目标List<RelationDTO>返回。
如果你的参数名和RelationDTO的属性名完全一致,上述@Mapping注解也可以省略,MapStruct会自动按名称匹配赋值。
内容的提问来源于stack exchange,提问作者xuweijsnj
相关产品推荐
相关产品推荐

