wxb2dyj
2020-03-18 21:42:39 +08:00
以下是我的方法
//CommonUtil.java
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
....
public static void copyNonNullProperties(Object src, Object target) {
BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}
private static String[] getNullPropertyNames(Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<>();
for (PropertyDescriptor pd : pds) {
String propertyName = pd.getName();
Object srcValue = src.getPropertyValue(propertyName);
if (srcValue == null) {
emptyNames.add(pd.getName());
}
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
//获取新 /旧员工信息,newEmployee 是新的员工信息,originalEmployee 是旧的员工信息
Employee originalEmployee = readFromYourMongoDB();
Employee newEmployee = readFromYourMySQL();
//该方法将会更新 originalEntity,而且只更新相对 newEntity 中变化的字段
CommonUtil.copyNonNullProperties(newEmployee , originalEmployee );
//重新保存 originalEmployee 到 MongoDB
ObjectId objectId = new ObjectId();
Date date = objectId.getDate();
//保存更新时间
originalEmployee.setUpdateTime(objectId.getDate());
employeeRepository.save(originalEmployee);