您的当前位置:首页正文

BeanUtils.copyProperties设置忽略null字段

来源:九壹网

1、

/**
     * 返回实体的所有 null 字段
     * @param source
     * @return
     */
    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        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()];
        String[] nullPropertyNames = emptyNames.toArray(result);
        return nullPropertyNames;
    }

2、

/**
 * 仅更新非null属性,防止原始值被null覆盖
 * @param source
 * @param id
 */
public Project updateNotNull(Project source){
    Project target = this.get(source.getId());
    BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    Project update = this.update(target);
    return update;
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Top