ModelMapper跳过一个字段

时间:2018-03-02 17:57:29

标签: modelmapper

我想在UserDTOUser之间进行映射,但不包括一个字段,请说city。我怎么能这样做,因为我虽然这种方法可行,但它没有:

ModelMapper modelMapper = new ModelMapper();

modelMapper.typeMap(UserDTO.class,User.class).addMappings(mp -> {
    mp.skip(User::setCity);
});

3 个答案:

答案 0 :(得分:1)

要使配置生效,需要添加:
modelMapper.getConfiguration()。setAmbiguityIgnored(true);

仅当目标字段与多个源字段匹配时,才为true。如果源目标之间存在1-1或0-1匹配,则跳过目标字段的设置将不执行上述操作。

答案 1 :(得分:0)

由于通用参数,我们无法使用lambda表达式。

ModelMapper modelMapper = new ModelMapper();
modelMapper.addMappings(new PropertyMap<Dto, Source>() {
                @Override
                protected void configure() {
                    skip(destination.getBlessedField());
                }
            });

答案 2 :(得分:0)

要使配置生效,需要添加:

modelMapper.getConfiguration().setAmbiguityIgnored(true);

例如

ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setAmbiguityIgnored(true);
modelMapper.addMappings(clientPropertyMap);
modelMapper.map(UserDTO, User);


PropertyMap<UserDTO, User> clientPropertyMap = new PropertyMap<UserDTO, User>() {
    @Override
    protected void configure() {
        skip(destination.getCity());
    }
};