首页 > 解决方案 > 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)

任何帮助表示赞赏!

标签: javacollectionsdtomapstruct

解决方案


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);


}


推荐阅读