java - MapStruct:如何跳过复制特定属性(该属性位于集合内且集合位于主实体内)

标签 java collections dto mapstruct

我正在使用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/

相关文章:

Java输入错误

java - AspectJ 拦截器不工作

c# - C# 有办法给我一个不可变的字典吗?

java - 在带有 JDBC 驱动程序的 Java 中使用准备好的语句和变量绑定(bind) Order By

java - 用于父/子关系和 DAO/DTO 模式的 Hibernate GenericDAO

java - JavaFX-我需要购买许可证并通过我的软件以在线共享它吗?

java - 如何反序列化大 JSON 文件 (~300Mb)

Java - 高效的集合管理

java - Spring-MVC、 hibernate : Creating DTO objects from Domain objects

c# - 我可以在两个项目中使用 Web Api 2 DTO 和 WCF DTO 吗?