Authored by liangyi.chen@yoho.cn

fix

1 package com.yoho.datasync.consumer.handler.helper; 1 package com.yoho.datasync.consumer.handler.helper;
2 2
  3 +import org.springframework.beans.BeanUtils;
  4 +
  5 +import java.lang.reflect.Field;
  6 +import java.util.Arrays;
  7 +import java.util.HashSet;
  8 +import java.util.Set;
  9 +
3 public class BeanCopyUtils { 10 public class BeanCopyUtils {
  11 +
  12 + /**
  13 + * 当一条记录需要更新的字段较多时采用全量更新
  14 + *将一个对象的字段值非空的属性值拷贝到一个目标对象,主要用于数据库的更新操作
  15 + * @param sourceObj 待更新对象
  16 + * @param targetObj 数据库查出来的对象
  17 + * @param <T> 目的对象类型
  18 + * @return 目的对象实例, 拷贝之后的结果
  19 + */
  20 + public static <T> T copyNonNullProperties(Object sourceObj, Object targetObj, Class<T> clazz ) {
  21 + if(sourceObj == null || targetObj == null){
  22 + return null;
  23 + }
  24 + try {
  25 + BeanUtils.copyProperties(sourceObj,targetObj,getNullProperties(sourceObj));
  26 + } catch (Exception e) {
  27 + e.printStackTrace();
  28 + return null;
  29 + }
  30 + return (T)targetObj;
  31 + }
  32 +
  33 + private static String[] getNullProperties(Object src) throws Exception{
  34 + Field[] fields = src.getClass().getDeclaredFields();
  35 + Set<String> emptyName=new HashSet<>();
  36 + if (fields == null || fields.length == 0) {
  37 + throw new Exception();
  38 + }
  39 + Arrays.stream(fields).forEach(field -> {
  40 + try {
  41 + field.setAccessible(true);
  42 + Object srcValue = field.get(src);
  43 + if(srcValue == null) emptyName.add(field.getName());
  44 + } catch (Exception e) {
  45 + e.printStackTrace();
  46 + throw new IllegalArgumentException();
  47 + }
  48 + });
  49 + String[] result=new String[emptyName.size()];
  50 + return emptyName.toArray(result);
  51 +
  52 + }
  53 +
4 } 54 }