Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modelmapper null value skip

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?

like image 692
AchuSai Avatar asked Dec 14 '17 17:12

AchuSai


People also ask

Does ModelMapper use reflection?

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.

What is TypeMap in Java?

TypeMap() Creates a type map in which the keys match both subclasses and subinterfaces.

What is the use of ModelMapper in Java?

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.


Video Answer


3 Answers

Have you tried this configuration:

modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
like image 57
TequilaLime Avatar answered Oct 26 '22 10:10

TequilaLime


I'd rather in this way:

@Configuration
public class ModelMapperConfig {

    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setSkipNullEnabled(true);

        return modelMapper;
    }
}
like image 28
Felipe Pereira Avatar answered Oct 26 '22 11:10

Felipe Pereira


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?

like image 44
Dasha Buzovska Avatar answered Oct 26 '22 11:10

Dasha Buzovska