【问题标题】:Set parent target to null if source is null in MapStruct如果 MapStruct 中的源为空,则将父目​​标设置为空
【发布时间】:2018-06-16 20:19:55
【问题描述】:

我有以下映射

@Mappings({
        @Mapping(source = "id", target = "id"),
        @Mapping(source = "childId", target = "child.id")
})
Entity objectDtoToEntity(ObjectDTO objectDTO);

如何配置我的 Mapper 或 Mappings,以便当我将 childId 设置为 null 时,目标 Entity.child 将设置为 null 而不是 Entity.child.id?

【问题讨论】:

    标签: java mapstruct


    【解决方案1】:

    发现对我来说不是一个非常优雅的解决方案,而是可行的解决方案。

    先把接口改成抽象类再添加@AfterMapping

    @Mappings({
            @Mapping(source = "id", target = "id"),
            @Mapping(source = "childId", target = "child.id")
    })
    public abstract Entity objectDtoToEntity(ObjectDTO objectDTO);
    
    
    @AfterMapping
    public Entity doAfterMapping(@MappingTarget Entity entity) {
        if (entity != null && entity.getChild().getId() == null) {
            entity.setChild(null);
        }
        return entity;
    }
    

    【讨论】:

    • 目前这是唯一的方法。这个确切的问题有一个未解决的问题。看看#1166
    • 这里有什么更新可以更优雅地实现这个案例吗?到目前为止,这个问题被问到已经超过 2 年了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 2012-09-01
    相关资源
    最近更新 更多