7
Class A {
    private String a;
    private String b;
    private B innerObject;
}
Class B {
    private String c;
}

就我而言, String b 可能带有一个空值。我的模型映射器配置如下:

ModelMapper mapper = new ModelMapper();
    mapper.getConfiguration()
    .setFieldMatchingEnabled(true)
    .setMatchingStrategy(MatchingStrategies.LOOSE)
    .setFieldAccessLevel(AccessLevel.PRIVATE)
    .setSkipNullEnabled(true)
    .setSourceNamingConvention(NamingConventions.JAVABEANS_MUTATOR);

当我映射对象时,我得到 b=null 值的目标对象。

试图远离此处显示的策略:SO-问题

我错过了什么?

4

3 回答 3

10

您是否尝试过此配置:

modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
于 2018-07-27T09:16:28.580 回答
2

我宁愿这样:

@Configuration
public class ModelMapperConfig {

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

        return modelMapper;
    }
}
于 2020-06-24T17:47:21.960 回答
1

看来,这不可能。

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);
}

我用下一个包装函数解决了它。

private static <D> D map(Object source, Type destination) {
    return source == null ? null : mapper.map(source, destination);
}

也检查这个问题Modelmapper: How to apply custom mapping when source object is null?

于 2020-06-04T13:10:48.897 回答