Handling null values while deepmapping fields

29 views
Skip to first unread message

Karsten Ohme

unread,
Dec 8, 2017, 12:17:40 AM12/8/17
to modelmapper
Hi,

is modelmapper transparently handling null values to prevent nullpointerexception or do I have to cover all these cases on my own?

An example:

typeMap.addMappings(
 mapper
-> mapper.<String>map(
 src
-> src.getLead().getBusiness().getName(), (dest, v) -> {dest.companyName= v;}));

if src.getLead().getBusiness()is null, will this be gracefully handled? If not, what options are included in modelmapper to deal 
with this common scenario while deep mapping objects?

Regards,
Karsten

Chun Han Hsiao

unread,
Dec 10, 2017, 9:27:08 PM12/10/17
to modelmapper
Hi Karsten,

ModelMapper will handle null well for deep property, so you can just mapped it!
But in you code, I think you should use setter (dest, v) -> { dest.setCompanyName(v); } instead of field assignment. AFAIK, TypeMap.addMappings is only support for getter/setters method calls.

Regards,
Chun Han

Karsten Ohme於 2017年12月8日星期五 UTC+8下午1時17分40秒寫道:

Karsten Ohme

unread,
Dec 10, 2017, 9:36:23 PM12/10/17
to modelmapper
Hi,

thanks for you answer. ModelMapper should also supports field mappings, at least I have found modelMapper.getConfiguration().setFieldMatchingEnabled(true); I hope this works.
Also, I have handled for now the checks for nullness in the lambda expression, e.g. 

src -> {
 
if (src.getLead().getBusiness() != null) {
 
return src.getLead().getBusiness().getName();
 
}
 
return null;
}

I have to check if your hint also works.

Regards,
Karsten

Chun Han Hsiao

unread,
Dec 11, 2017, 9:35:05 PM12/11/17
to modelmapper
Hi Karsten,

Yeah, it will be better to support field mapping for this new feature.
And for your code snippet, I don't think you need to do the null check, please just try src -> src.getLead().getBusiness().getName() and I think it will work fine.

Regards,
Chun Han

Karsten Ohme於 2017年12月11日星期一 UTC+8上午10時36分23秒寫道:
Reply all
Reply to author
Forward
0 new messages