简体   繁体   English

如果源为空,如何防止 MapStruct 创建实体?

[英]How to prevent MapStruct from creating entity if the source is null?

Is there a way to prevent MapStruct from creating an object if the source is null?如果源为空,是否有办法阻止 MapStruct 创建对象?

Existing answers I've found explain how to do it with the object but not in a nested path.我发现的现有答案解释了如何使用对象而不是在嵌套路径中进行操作。 Here is an example.这是一个例子。

The mapper映射器

@Mapping(target = "manufacturer.id", source = "manufacturerId")
CarEntity toEntity(CarDTO carDto);

The generated code, in comments what Mapstruct misses生成的代码,在注释中 Mapstruct 遗漏了什么

protected ManuFacturerEntity carDTOToCarEntity(CarDTO carDto) {
    if ( carDto == null ) {
        return null;
    }

    // what I'd like mapstruct to generate
    if (cardDto.manufacturerId == null) {
        return null;
    }

    ManufactureurEntity manufacturerEntity = new ManufacturerEntity();
    manufactureurEntity.id = carDto.manufacturerId;
    return panneaumanufacturerEntity;
}

I know I probably can do it with @BeforeMapping but it doesn't just feel the right way to do it.我知道我可能可以使用@BeforeMapping来做到这一点,但它不仅仅是感觉正确的方法。

You can change the mapping target to manufacturer and define a default method for mapping the manufacturerId to the ManufacturerEntity object that creates the object only if manufacturerId is not null .您可以将映射目标更改为manufacturer并定义默认方法以将manufacturerId映射到仅当manufacturerId不为null时才创建该对象的ManufacturerEntity对象。

@Mapping(target = "manufacturer", source = "manufacturerId")
CarEntity toEntity(CarDTO carDto);

default ManufacturerEntity mapManufacturerId(Long manufacturerId){
    if (manufacturerId == null) return null;
    ManufacturerEntity manufacturerEntity = new ManufacturerEntity();
    manufacturerEntity.id = manufacturerId;
    return manufacturerEntity;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM