How to ignore null values using springframework BeanUtils copyProperties?

后端 未结 6 1326
悲哀的现实
悲哀的现实 2020-12-01 00:09

I would like to know how to copy the properties from an Object Source to an Object Dest ignoring null values​​ using Spring Framework.

I actually use Apache beanutil

6条回答
  •  醉酒成梦
    2020-12-01 00:43

    I advise you to use ModelMapper.

    This is a sample code that solves your doubt.

          ModelMapper modelMapper = new ModelMapper();
    modelMapper.getConfiguration().setSkipNullEnabled(true).setMatchingStrategy(MatchingStrategies.STRICT);
    
          Company a = new Company();
          a.setId(123l);
          Company b = new Company();
          b.setId(456l);
          b.setName("ABC");
    
          modelMapper.map(a, b);
    
          System.out.println("->" + b.getName());
    

    It should print the B value. But if you set the "A" name, the result is a print of "A" value.

    The secret is changing the value of SkipNullEnabled to true.

    ModelMapper

    ModelMapper MVN

提交回复
热议问题