BeanUtils.copyProperties(Object source, Object target)方法可以快速的將source對象中的屬性賦值給target對象。當我們對java實體執行相關操作時,使用BeanUtils工具可以快速執行新增、修改時對實體屬性的賦值操作。
但是若source對象中的屬性爲null時,target中相應的屬性也會被修改爲null,有時候這可能不是我們希望的結果。
編寫如下工具類,可以使BeanUtils.copyProperties()拷貝屬性時,忽略空值。
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);
}
BeanUtils.copyProperties(source, target, BeanOperateUtil.gainNullPropertyNames(source));
源代碼如下:拷貝相應屬性時,會忽略source對象在ignoreProperties[]數組裏的屬性
public static transient void copyProperties(Object source, Object target, String ignoreProperties[])
throws BeansException
{
copyProperties(source, target, null, ignoreProperties);
}
注意事項:當生成uuid對象時,需先拷貝完form的屬性後,再設置對象id,不然對象id會被null覆蓋,新增對象會報錯。
TaEnterprise taEnterprise = new TaEnterprise();
BeanUtils.copyProperties(taEnterprise, form, BeanOperateUtil.gainNullPropertyNames(form));
taEnterprise.setEnterpriseid(FileUtil.getUUID());
enterpriseid = taEnterprise.getEnterpriseid();
getEntityManager().persist(taEnterprise);