BeanUtils.copyProperties()属性为null也会被复制,所以自己定义一个属性为null不复制的方法
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);
}
public static void copyPropertiesIgnoreNull(Object src, Object target){
BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}
T t1 = mongoRepository.findById((PK) field.get(t)).get();
copyPropertiesIgnoreNull(t,t1);
t1是数据库查出来的值,相当于serrvice.findone(id)了
t是传进来的对象(这边是泛型共用类)
copyPropertiesIgnoreNull 就是自己定义的方法,借助BeanUtils.copyProperties();(copyProperties默认是会把null的给替换掉)