如果源为空,有没有办法阻止 MapStruct 创建对象?
我找到的现有答案解释了如何使用对象而不是在嵌套路径中执行此操作。这是一个例子。
地图绘制者
@Mapping(target = "manufacturer.id", source = "manufacturerId")
CarEntity toEntity(CarDTO carDto);
生成的代码,在 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;
}
我知道我可能可以用
@BeforeMapping
做到这一点,但它不仅仅是感觉正确的方法。
您可以将映射目标更改为
manufacturer
并定义一个默认方法,用于将 manufacturerId
映射到 ManufacturerEntity
对象,仅当 manufacturerId
不是 null
时才会创建该对象。
@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;
}
经过我搜索了很多,我发现了https://github.com/mapstruct/mapstruct/issues/1306
在本期中他们说你应该使用此代码:
@Mapping(source = "id", target = "object.id")
Target toModel(Source source);
@AfterMapping
default void after(final @MappingTarget Target target, final Source source) {
if(source.getId() == null) {
target.setObject(null);
}
}