ModelMapper不忽略空值 [英] ModelMapper not ignoring null values
问题描述
我想对我的一个实体进行部分更新,但是如果一个属性为null,则要更新的实体也会将该值设置为null.我希望如果源中的属性为null,则保留源中的一个.
I want to do a partial update on one of my entities but if one propertie is null then the entity to be updated gets that value set to null too. I want that if a property from the source is null then to keep the one from the source.
我尝试过但没有运气:
@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
modelMapper.createTypeMap(String.class, Date.class);
modelMapper.addConverter(new StringToDate());
modelMapper.addConverter(new DateToString());
return modelMapper;
}
然后我像这样更新我的对象:
Then I update my object like this:
@Override
public void editUser(final User user) {
UserDocument userDocument = this.usersRepository.findByIdAndActivo(user.getId(), true)
.orElseThrow(UserNotFoundException::new);
userDocument = this.modelMapper.map(user, UserDocument.class);
this.usersRepository.save(userDocument);
}
user
对象的1个属性设置为null,而对象userDocument
的该属性带有值,那么当我将其保存在数据库中时,该值就消失了(因为它已转换为null).
The user
object has 1 property set at null while the object userDocument
has it with a value, then when I save it in the database that value is gone (because it has transformed into null).
有什么问题吗?
谢谢.
推荐答案
好的,这样配置就不是我想的目的.
Okay so that configuration isn't for the purpose I thought it was.
我通过将更新的对象与旧对象合并来解决了这个问题:
I've solved the issue by merging the updated object with the old one like this:
@Override
public void editUser(final User user) {
UserDocument userDocument = this.usersRepository.findByIdAndActivo(user.getId(), true)
.orElseThrow(UserNotFoundException::new);
this.modelMapper.map(user, userDocument);
this.usersRepository.save(userDocument);
}
这篇关于ModelMapper不忽略空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!