You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止MapStruct在源为Null时创建实体?含嵌套路径场景

阻止MapStruct在嵌套路径源为null时创建对象的方案

针对嵌套路径场景(比如通过manufacturerId映射manufacturer.id时,不想在manufacturerId为null时生成空的ManufacturerEntity),可以用以下两种更精准的方案替代@BeforeMapping:

方案一:使用@Mapping的condition属性

通过自定义判断方法,指定只有当源字段非null时才执行嵌套对象的映射:

@Mapper
public interface CarMapper {
    CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);

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

    // 自定义判断逻辑:仅当manufacturerId非null时才映射manufacturer对象
    default boolean hasManufacturerId(CarDTO carDto) {
        return carDto != null && carDto.getManufacturerId() != null;
    }
}

当manufacturerId为null时,condition返回false,MapStruct会跳过manufacturer字段的映射,直接将其设为null,不会创建空的ManufacturerEntity。

方案二:自定义嵌套对象的映射方法

显式编写从源对象到嵌套目标对象的映射方法,在方法内添加null判断逻辑:

@Mapper
public interface CarMapper {
    CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);

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

    // 自定义嵌套映射逻辑,直接控制对象创建时机
    default ManufacturerEntity mapManufacturer(CarDTO carDto) {
        if (carDto == null || carDto.getManufacturerId() == null) {
            return null;
        }
        ManufacturerEntity manufacturerEntity = new ManufacturerEntity();
        manufacturerEntity.setId(carDto.getManufacturerId());
        return manufacturerEntity;
    }
}

MapStruct会优先使用你自定义的mapManufacturer方法,而非自动生成默认的映射逻辑,完全符合你想要的判断逻辑。

这两种方案都比@BeforeMapping更精准,仅针对特定的嵌套映射场景生效,代码耦合度更低,逻辑更清晰。

内容的提问来源于stack exchange,提问作者Clemzd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 09:05:15