|
|
package com.yoho.datasync.consumer.handler.helper;
|
|
|
|
|
|
import org.springframework.beans.BeanUtils;
|
|
|
|
|
|
import java.lang.reflect.Field;
|
|
|
import java.util.Arrays;
|
|
|
import java.util.HashSet;
|
|
|
import java.util.Set;
|
|
|
|
|
|
public class BeanCopyUtils {
|
|
|
|
|
|
/**
|
|
|
* 当一条记录需要更新的字段较多时采用全量更新
|
|
|
*将一个对象的字段值非空的属性值拷贝到一个目标对象,主要用于数据库的更新操作
|
|
|
* @param sourceObj 待更新对象
|
|
|
* @param targetObj 数据库查出来的对象
|
|
|
* @param <T> 目的对象类型
|
|
|
* @return 目的对象实例, 拷贝之后的结果
|
|
|
*/
|
|
|
public static <T> T copyNonNullProperties(Object sourceObj, Object targetObj, Class<T> clazz ) {
|
|
|
if(sourceObj == null || targetObj == null){
|
|
|
return null;
|
|
|
}
|
|
|
try {
|
|
|
BeanUtils.copyProperties(sourceObj,targetObj,getNullProperties(sourceObj));
|
|
|
} catch (Exception e) {
|
|
|
e.printStackTrace();
|
|
|
return null;
|
|
|
}
|
|
|
return (T)targetObj;
|
|
|
}
|
|
|
|
|
|
private static String[] getNullProperties(Object src) throws Exception{
|
|
|
Field[] fields = src.getClass().getDeclaredFields();
|
|
|
Set<String> emptyName=new HashSet<>();
|
|
|
if (fields == null || fields.length == 0) {
|
|
|
throw new Exception();
|
|
|
}
|
|
|
Arrays.stream(fields).forEach(field -> {
|
|
|
try {
|
|
|
field.setAccessible(true);
|
|
|
Object srcValue = field.get(src);
|
|
|
if(srcValue == null) emptyName.add(field.getName());
|
|
|
} catch (Exception e) {
|
|
|
e.printStackTrace();
|
|
|
throw new IllegalArgumentException();
|
|
|
}
|
|
|
});
|
|
|
String[] result=new String[emptyName.size()];
|
|
|
return emptyName.toArray(result);
|
|
|
|
|
|
}
|
|
|
|
|
|
} |
...
|
...
|
|