【问题标题】:Mapping DTO an Entity, leave entity null if all your field is null将 DTO 映射到实体,如果您的所有字段为空,则将实体留空
【发布时间】:2022-01-10 14:54:11
【问题描述】:

我的实体是返回字段 null 示例:EntityTest{id=null, name=null}

但我需要,如果所有字段都为空,则返回 EntityTest = null

测试实体

@Entity
@Table(name="TestEntity")
public class TestEntity {
    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name="test_name")
    private String testName;
}

TestEntityDto

public class TestEntityDto {

    private long id;
    private String test_name;
}

TestEntityMapper

@Mapper
public interface TestEntityMapper {
    TestEntity TestEntityDTOToTestEntity(TestEntityDTO testEntityDTO);

实施

testEntityDTO.setId(null);
testEntityDTO.setNameTest(null);
TestEntity testEntity = TestEntityMapper.TestEntityDTOToTestEntity(testEntityDTO);

实际结果:

EntityTest{id=null, name=null}

预期结果:

EntityTest = null

【问题讨论】:

  • 这不是它的工作原理。

标签: java spring-boot spring-data-jpa mapstruct modelmapper


【解决方案1】:

在即将发布的 1.5 版本中,MapStruct 添加了对条件映射的支持。在当前发布的 1.5 Beta2 中,不支持条件支持参数。但是,有一个开放的enhancement request 可以为源参数添加它。

这意味着您可以执行以下操作:

public class MappingUtils {

    @Condition
    public static boolean isPresent(TestEntityDTO dto) {
        if (dto == null) {
            return false;
        }

        return dto.getId() != null || dto.getName() != null;
    }

}

这意味着你可以有一个像这样的映射器:

@Mapper(uses = MappingUtils.class)
public interface TestEntityMapper {

    TestEntity testEntityDTOToTestEntity(TestEntityDTO testEntityDTO);

}

实现如下:

public class TestEntityMapperImpl implements {

    @Override
    public TestEntity testEntityDTOToTestEntity(TestEntityDTO dto) {
        if (!MappingUtils.isPresent(dto)) {
            return null
        }

        // the rest of the mapping
    }
}

注意:这在发布版本中尚不可能,但这就是它的工作方式。除了这个未来的解决方案之外,没有其他现成的 MapStruct 解决方案。

【讨论】:

    【解决方案2】:

    我建议只执行 toString 来检查全部为空的情况:

    toString(){"id:"+id+",name:"+name;}
    

    所以如果返回 "id:null,name:null" 那么你可以确定它是 null 并在检查等于后返回 null

    【讨论】:

    • 但是你说映射后,DTO 到实体?
    • 是的,这可以在映射后完成
    • 谢谢你,这对我有用
    • @AiltonDaCosta 欢迎您
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2017-09-17
    • 2018-09-13
    • 2022-01-02
    • 1970-01-01
    相关资源
    最近更新 更多