Mapstruct – 当目标为null时忽略映射

huangapple go评论57阅读模式
英文:

Mapstruct - ingore mapping when target is null

问题

如果 engine 为空,我不想进行映射。我该怎么做?

@Mapper
public interface CarMapper {

    @Mapping(target = "engine", source = "device")
    void updateCarFromDto(CarDto carDto, @MappingTarget Car car);
}
英文:

Consider the below codes, if engine is null, I don't want to map it. How can I do it?

@Mapper
public interface CarMapper {

    @Mapping(target = "engine", source = "device")
    void updateCarFromDto(CarDto carDto, @MappingTarget Car car);
}

答案1

得分: 1

我们可以使用 ignore@AfterMapping

@Mapper
public interface CarMapper {

    @Mapping(target = "engine", ignore = true)
    void updateCarFromDto(CarDto carDto, @MappingTarget Car car);

    @AfterMapping
    default void update(CarDto carDto, @MappingTarget Car car) {
        if (car == null || carDto == null) {
            return;
        }

        if (car.getEngine() != null)
            car.setEngine(carDto.getDevice());
            
    }
}
英文:

We can use ignore and @AfterMapping.

@Mapper
public interface CarMapper {

    @Mapping(target = "engine", ignore = "true")
    void updateCarFromDto(CarDto carDto, @MappingTarget Car car);

    @AfterMapping
    default void update(CarDto carDto, @MappingTarget Car car) {
        if(car == null || carDto == null) {
            return;
        }

        if(car.getEngine != null)
            car.setEngine(carDto.getDevice);
            
    }
}

huangapple
  • 本文由 发表于 2023年5月25日 04:59:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76327367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定