How to ignore null values using springframework BeanUtils copyProperties?
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
Java 8 version of getNullPropertyNames method from alfredx's post:
public static String[] getNullPropertyNames(Object source) {
final BeanWrapper wrappedSource = new BeanWrapperImpl(source);
return Stream.of(wrappedSource.getPropertyDescriptors())
.map(FeatureDescriptor::getName)
.filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null)
.toArray(String[]::new);
}
You can create your own method to copy properties while ignoring null values.
public static String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
// then use Spring BeanUtils to copy and ignore null using our function
public static void myCopyProperties(Object src, Object target) {
BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}