Always map null object to null

Vjeetje picture Vjeetje · Feb 11, 2013 · Viewed 8.6k times · Source

I'm looking for a way to map every object that is null to null instead of "org.dozer.MappingException: Source object must not be null" error. I don't want to enumerate every class and say that null maps to null, I want to specify this as a general rule.

Answer

Dmitry Buzdin picture Dmitry Buzdin · Feb 11, 2013

This one is a generic exception saying that you should not pass null object as a top level bean to mapper.map(src, dest) method. So putting guard check before invoking Dozer should help.

if (src == null) return null;
return dozer.map(src, dest);

In addition, 'map-null' policy is enabled by default, but it applies only to elements inside the bean you want to map (not top-level). So Dozer will properly map 'user.id' if it is null value. In the next version there will be a possibility to apply 'map-null' on global level as well without specifying each class. However this would only help to disable null mapping, since it is enabled by default.