DozerBeanMapper:忽略来自源的空值
DozerBeanMapper: Ignore Null values from Source
在我的 Java 项目中,我使用 org.dozer.BeanMapper 将复杂的源对象合并到具有相同类型的目标对象中:
sourceObject.valueA = null
sourceObject.valueB = B1
sourceObject.valueC = C1
destinationObject.valueA = A2
destinationObject.valueB = null
destinationObject.valueC = C2
beanMerger.map(sourceObject, destinationObject);
这导致我的 destinationObject 中的这个值:
destinationObject.valueA: null
destinationObject.valueB: B1
destinationObject.valueC: C1
我可以配置 BeanMapper 使其不覆盖具有空值的字段吗?我的预期结果应该是:
destinationObject.valueA: A2
destinationObject.valueB: B1
destinationObject.valueC: C1
甚至更好(不要触摸目标对象的设置值)
destinationObject.valueA: A2
destinationObject.valueB: B1
destinationObject.valueC: C2
我找到了解决方案:
beanMerger.addMapping(
new BeanMappingBuilder() {
protected void configure() {
mapping(MyObjectDTO.class, MyObjectDTO.class, TypeMappingOptions.mapNull(false));
}
});
在我的 Java 项目中,我使用 org.dozer.BeanMapper 将复杂的源对象合并到具有相同类型的目标对象中:
sourceObject.valueA = null
sourceObject.valueB = B1
sourceObject.valueC = C1
destinationObject.valueA = A2
destinationObject.valueB = null
destinationObject.valueC = C2
beanMerger.map(sourceObject, destinationObject);
这导致我的 destinationObject 中的这个值:
destinationObject.valueA: null
destinationObject.valueB: B1
destinationObject.valueC: C1
我可以配置 BeanMapper 使其不覆盖具有空值的字段吗?我的预期结果应该是:
destinationObject.valueA: A2
destinationObject.valueB: B1
destinationObject.valueC: C1
甚至更好(不要触摸目标对象的设置值)
destinationObject.valueA: A2
destinationObject.valueB: B1
destinationObject.valueC: C2
我找到了解决方案:
beanMerger.addMapping(
new BeanMappingBuilder() {
protected void configure() {
mapping(MyObjectDTO.class, MyObjectDTO.class, TypeMappingOptions.mapNull(false));
}
});