java - mapstruct 如何将对象列表转换为接口列表?
问题描述
我有以下接口和类
public interface Fruit { ... }
public class AppleDto implements Fruit {...}
public class AppleEntity { ... }
我创建了一个映射器,它将List
of转换AppleEntity
为List
ofAppleDto
但我需要返回类型为List
of Fruit
。
@Mapper
public interface FruitsMapper {
FruitsMapper INSTANCE = Mappers.getMapper(FruitsMapper.class);
@IterableMapping(elementTargetType = AppleDto.class)
List<Fruit> entityToFruits(List<AppleEntity> entity);
}
它不允许我转换为接口列表并给出错误。有没有合适的方法来实现我所需要的?
解决方案
您需要在 和 之间定义一个映射方法,AppleEntity
并Fruit
通过以下方式定义结果类型@BeanMapping#resultType
在你的情况下,它看起来像:
@Mapper
public interface FruitsMapper {
FruitsMapper INSTANCE = Mappers.getMapper(FruitsMapper.class);
@BeanMapping(resultType = AppleDto.class)
Fruit map(AppleEntity entity);
List<Fruit> entityToFruits(List<AppleEntity> entity);
}
使用@IterableMapping#elementTargetType
不是您所期望的。当有多种映射方法可能时,它只是一个选择标准。从它的javadoc:
Specifies the type of the element to be used in the result of the mapping method in case multiple mapping
methods qualify.
推荐阅读
- reactjs - NextJs 路由器 404 从 Digital Ocean 刷新
- c# - 尝试使用键输入重置部分程序
- github-actions - 为什么我在此 GitHub 操作中收到“Unexpected value ''”错误?
- mongodb - 如何通过 objectID 引用其他文档数据?
- awk - 如何在 Awk 中使用单个正则表达式提取多个字符串
- google-apps-script - Google 文档脚本中的侧边栏按钮 onClick 不会触发
- css - Nginx css 未加载用于 Rewrite 与 $
- arrays - 如何将嵌套数组中的值相乘...乘以另一个数组中的值(在 Google 表格中)?
- r - 按列和组删除异常值
- javascript - 检查用户位置(城市,州