Java – How to exclude object properties

How to exclude object properties… here is a solution to the problem.

How to exclude object properties

I use the Orika mapper to map two beans. I want to exclude the billingSummary.billableItems property when mapping. I’m trying the following option but it doesn’t work.

Does it help?

public class Cart {
       private String id;
       private String name;
       private BillingSummary billingSummary;
       private String address;
       with getter and setter methods
    }

public class BillingSummary {
       private String billingItem;
       private String billingItemId;
       private BillableItems billableItems;
       ...
        with getter setter methods
   }

FilteredCart is same as Cart.

public class FilteredCart { 
        private String id;
        private String name;
        private BillingSummary billingSummary;
        private String address;
        with getter and setter methods
    } 

@Component   
public class CartMapper extends ConfigurableMapper {
        @Override
        public void configure(MapperFactory mapperFactory) {
        mapperFactory.classMap(Cart.class,FilteredCart.class).exclude("billingSummary.billableItems").byDefault().register();
        }
}

Solution

What you can do is add another mapping to mapperFactory to define how you want to map the BillingSummary to itself. This way, when mapping from Cart to FilteredCart, you can configure exclusions to map billableItems.

As a result, your CartMapper will look like this:

@Component   
public class CartMapper extends ConfigurableMapper {

@Override
    public void configure(MapperFactory mapperFactory) {
        mapperFactory.classMap(BillingSummary.class, BillingSummary.class).exclude("billableItems").byDefault().register();
        mapperFactory.classMap(Cart.class,FilteredCart.class).byDefault().register();
    }
}

Related Problems and Solutions