Class A {
private String a;
private String b;
private B innerObject;
}
Class B {
private String c;
}
In my case, String b might come in with a null value. My modelmapper configuration is like below:
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration()
.setFieldMatchingEnabled(true)
.setMatchingStrategy(MatchingStrategies.LOOSE)
.setFieldAccessLevel(AccessLevel.PRIVATE)
.setSkipNullEnabled(true)
.setSourceNamingConvention(NamingConventions.JAVABEANS_MUTATOR);
when I map the object, I get the target object with b=null value.
Trying to stay away from a strategy shown here: SO- Question
What am I missing?
I believe that ModelMapper is based on reflection and performs the mapping during runtime. Whereas MapStruct is a code generator which generates the mapping code (java classes) during compilation time. So naturally if you are worried about performance then MapStruct is the clear choice.
TypeMap() Creates a type map in which the keys match both subclasses and subinterfaces.
ModelMapper, is an object-to-object framework that converts Java Beans (Pojos) from one representation to another. It automates different object mappings with a "convention follows configuration" approach allowing at the same time advanced functionality for cases with special needs.
Have you tried this configuration:
modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
I'd rather in this way:
@Configuration
public class ModelMapperConfig {
@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setSkipNullEnabled(true);
return modelMapper;
}
}
Looks, like it's not possible.
public <D> D map(Object source, Class<D> destinationType) {
Assert.notNull(source, "source");
Assert.notNull(destinationType, "destinationType");
return this.mapInternal(source, (Object)null, destinationType (String)null);
}
I solved it with next wrapper function.
private static <D> D map(Object source, Type destination) {
return source == null ? null : mapper.map(source, destination);
}
Check this question too Modelmapper: How to apply custom mapping when source object is null?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With