java - MapStruct:如何从复制属性在集合内且集合在主实体内的位置跳过特定属性
问题描述
我正在使用 mapstruct 更新现有的 bean。下面是我的豆子。如您所见,我的 Entity bean 有一个 AnotherEntity bean 的集合。
public class Entity
{
private Integer id;
private String name;
private List<AnotherEntity> anotherEntityList = new ArrayList<AnotherEntity>();
//getters & setters
}
public class AnotherEntity
{
private Integer id;
private String text;
//getters & setters
}
下面是我如何定义映射。
Entity updateEntityWithEntity(final Entity sourceEntity, @MappingTarget final Entity targetEntity);
更新后,我希望 mapstruct 跳过 AnotherEntity bean 中的 id 属性。目前它正在清除现有集合并使用来自源的值创建一个新集合。
如果我添加以下内容
@Mapping(target = "anotherEntityList", ignore = true)
它忽略了整个集合。但我想要收藏,但只忽略 id 属性。像这样的东西。@Mapping(target = "anotherEntityList.id", ignore = true)
任何帮助表示赞赏!
解决方案
MapStruct 无法生成列表映射。它不会知道用户的实际意图。看看这个以获得更多解释。
但是假设列表都是有序的,并且元素 0 需要映射到目标元素 0、1 到 1 等。
你可以这样做:
@Mapper
public interface MyMapper{
// you probably don't need the return, right?
void updateEntityWithEntity(Entity sourceEntity, @MappingTarget Entity targetEntity);
// you need to implement the list merging yourself.. MapStruct has no clue what you intent here
default updateList( List< AnotherEntity > sourceList, @MappingTarget List< AnotherEntity> targetList ) {
for ( int i=0; i<sourceList.size(); i++ ) {
updateAnotherEntityWithAnotherEntity( sourceList.get( i ), targetList.get( i ) );
}
}
// used by above code in
@Mapping( target = "id", ignore = true )
void updateAnotherEntityWithAnotherEntity(AnotherEntity sourceEntity, @MappingTarget AnotherEntity targetEntity);
}
推荐阅读
- javascript - RequestBody 在控制器中为空
- javascript - jQuery宽度函数参数不起作用
- c++ - 有没有办法用 catch 框架来比较流或文件?
- microsoft-graph-api - MS Graph API 照片端点不适用于组的应用程序权限
- android - 防止登录成功后出现登录页面
- docker - Windows 7 docker toolbox - dockerizing jenkins - 无法安装插件
- c# - 如何在c#中反序列化json对象数组
- php - 使用所有者=值从使用php的json代码获取所有数据
- javascript - html打印表格将总值添加为每页的页脚
- python - 如何在python的决策树中使用分类数据