英文:
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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论