Set parent target to null if source is null in MapStruct

后端 未结 1 875
南方客
南方客 2021-01-27 11:45

I have the following Mappings

@Mappings({
        @Mapping(source = \"id\", target = \"id\"),
        @Mapping(source = \"childId\", target = \"child.id\")
})
E         


        
相关标签:
1条回答
  • 2021-01-27 12:31

    Found not a very elegant solution as for me but working solution.

    First change interface to abstract class then add @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;
    }
    
    0 讨论(0)
提交回复
热议问题