8
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?

Andrew Nepogoda
  • 1,825
  • 17
  • 24
AchuSai
  • 93
  • 1
  • 1
  • 6

3 Answers3

10

Have you tried this configuration:

modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
TequilaLime
  • 109
  • 1
  • 6
6

I'd rather in this way:

@Configuration
public class ModelMapperConfig {

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

        return modelMapper;
    }
}
Felipe Pereira
  • 1,368
  • 16
  • 26
  • How can I make this work for only one specific mapping? Only when mapping class `A` to class `B`, I want this to be enabled. – Shubham Dhingra Dec 26 '22 at 14:08
  • 1
    @ShubhamDhingra you can check this [code](https://github.com/felipealvesgnu/ala-api/blob/master/src/main/java/br/org/ala/api/mapper/AssociadoMapper.java), where there some mappings handling specific situations to DTO Objects . – Felipe Pereira Dec 28 '22 at 01:19
1

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?