Search code examples
javajavabeansdozer

Dozer only copy if receiving bean mapped field is null


How do a I configure Dozer so that it will only copy the value from one field in bean a to a field in bean b if the field in bean b is null? I am using dsl config

mapping(FirstGivingPayloadV1.Payload.class, Nonprofit.class, oneWay(),
        mapNull(false), mapId("firstGivingPayloadV1"))
        .fields("latitude", "latitude")
        .fields("longitude", "longitude")
        .fields("revoked", "isNonProfitStatusVerified");
        .fields("url", "websiteUrl"); // only copy url if webSiteURL == null or is empty

Solution

  • Write a custom converter for this field conversion. Custom converter should check if field in bean b is null and if it is copy field a to it.

    From Dozer documentation:

    In the example below, Dozer will invoke the custom converter to perform the field mapping.

    <mapping>
      <class-a>org.dozer.vo.SimpleObj</class-a>
      <class-b>org.dozer.vo.SimpleObjPrime2</class-b>    
      <field custom-converter-id="CustomConverterWithId">
        <a>field1</a>
        <b>field1Prime</b>
      </field>
    </mapping>  
    

    In custom converter you have access to destination object and you can check if it is null, look at the convert method signature:

    public class TestCustomConverter implements CustomConverter {
     public Object convert(Object destination, Object source, Class destClass, Class sourceClass) {...