这里使用的是Spring提供的BeanUtils的工具类(commons-lang3可参考)。在做数据变更的时候,使用BeanUtils.copyProperties(newdata,dbdata)进行数据变更的时候,由于前台展示的数据不完整。导致前台传递的数据将后台的原始数据全部覆盖掉。那么如何解决这种null值的覆盖呢。BeanUtils.copyProperties()可以通过添加可变长参数忽略掉具体的某些不需要更新的字段。比如BeanUtils.copyProperties(newdata,dbdata,“id”,“password”)。
那么如果字段比较多,使用上面的方法简直要疯掉了。有没有更好的方法呢?
可以自己拓展一个方法,汇总值为null的数据。
public static String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(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);
}