import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import java.beans.PropertyDescriptor;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* @author liyongfei
*/
public class UpdateTool {
private static final String JAVA_LANG_LONG = "java.lang.Long";
private static final String JAVA_LANG_INTEGER = "java.lang.Integer";
private static final String JAVA_LANG_STRING = "java.lang.String";
public static final String MODIFY_TIME = "modifyTime";
/**
* 将目标源中不为空的字段过滤,将数据库中查出的数据源复制到提交的目标源中
*
* @param source 用id从数据库中查出来的数据源
* @param target 提交的实体,目标源
*/
public static void copyNotNullProperties(Object source, Object target) {
BeanUtils.copyProperties(source, target, getNullProperties(source));
}
/**
* 自动设置修改时间
*
* @param target
*/
public static Object setModifyTime(Object target) {
BeanWrapper srcBean = new BeanWrapperImpl(target);
try {
srcBean.setPropertyValue(MODIFY_TIME, new Date());
}catch (BeansException e){
e.printStackTrace();
System.out.println("no properties of modifyTime -- bye bye");
}
return target;
}
/**
* @param target 目标源数据
* @return 将目标源中不为空的字段取出
*/
private static String[] getNullProperties(Object target) {
BeanWrapper srcBean = new BeanWrapperImpl(target);
PropertyDescriptor[] propertyDescriptors = srcBean.getPropertyDescriptors();
Set<String> noEmptyName = new HashSet<>();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Class<?> propertyType = propertyDescriptor.getPropertyType();
//对属性专门过滤 出现int为0情况
if (propertyType.getName().equals(JAVA_LANG_LONG)) {
Long longValue = (Long) srcBean.getPropertyValue(propertyDescriptor.getName());
if (longValue == null || longValue == 0L) {
noEmptyName.add(propertyDescriptor.getName());
}
} else if (propertyType.getName().equals(JAVA_LANG_INTEGER)) {
Integer intValue = (Integer) srcBean.getPropertyValue(propertyDescriptor.getName());
if (intValue == null || intValue == 0) {
noEmptyName.add(propertyDescriptor.getName());
}
} else if (propertyType.getName().equals(JAVA_LANG_STRING)) {
String stringValue = (String) srcBean.getPropertyValue(propertyDescriptor.getName());
if (stringValue == null || StringUtils.isBlank(stringValue)) {
noEmptyName.add(propertyDescriptor.getName());
}
} else {
Object object = srcBean.getPropertyValue(propertyDescriptor.getName());
if (object == null) {
noEmptyName.add(propertyDescriptor.getName());
}
}
}
String[] result = new String[noEmptyName.size()];
return noEmptyName.toArray(result);
}
}