BeanUtils.copyProperties參數爲null的時候不復制

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的給替換掉)

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章