Search code examples
javamappingdozer

DozerBeanMapper: Ignore Null values from Source


In my Java project I use the org.dozer.BeanMapper to merge a complex source object into a destination object with the same type:

sourceObject.valueA = null
sourceObject.valueB = B1
sourceObject.valueC = C1

destinationObject.valueA = A2
destinationObject.valueB = null
destinationObject.valueC = C2

beanMerger.map(sourceObject, destinationObject);

This results to this values in my destinationObject:

destinationObject.valueA: null
destinationObject.valueB: B1
destinationObject.valueC: C1 

can i configure the BeanMapper in a way that it should not override fields with a null value? My expected result should be:

destinationObject.valueA: A2
destinationObject.valueB: B1
destinationObject.valueC: C1 

or even better (dont touch set values of the destination object)

destinationObject.valueA: A2
destinationObject.valueB: B1
destinationObject.valueC: C2

Solution

  • I found the solution:

    beanMerger.addMapping(
      new BeanMappingBuilder() {
        protected void configure() {
           mapping(MyObjectDTO.class, MyObjectDTO.class, TypeMappingOptions.mapNull(false));
        }
      });