我正在使用mapstruct 更新现有的bean。下面是我的 bean 。正如您所看到的,我的实体 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 无法生成列表映射。它不知道用户的实际意图是什么。看看this以获得更多解释。
但假设列表都是有序的,并且元素 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);
}
关于java - MapStruct:如何跳过复制特定属性(该属性位于集合内且集合位于主实体内),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56869457/