使用 BeanUtils.copyProperties属性拷贝

配合Beanutils设置对源对象中空的元素不进行复制,避免了目标对象某属性原本不为空,赋值后为空

自定义工具类

java 复制代码
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.HashSet;
import java.util.Set;

public class MyBeanUtils {

    public static void copyProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }


    /**
     * 配合Beanutils设置对源对象中空的元素不进行复制,避免了目标对象某属性原本不为空,赋值后为空
     */
    public static String[] getNullPropertyNames(Object source) {
        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);
    }


}
相关推荐
没有bug.的程序员1 小时前
Spring Cloud Alibaba 生态总览
java·开发语言·spring boot·spring cloud·alibaba
小坏讲微服务7 小时前
Spring Boot整合Redis注解,实战Redis注解使用
spring boot·redis·分布式·后端·spring cloud·微服务·mybatis
xie_pin_an7 小时前
MyBatis-Plus 实战:MPJLambdaWrapper 多表联查用法全解析
java·spring boot·spring·mybatis
一个儒雅随和的男子8 小时前
多级缓存解决方案
spring boot·缓存
橘子海全栈攻城狮8 小时前
【源码+文档+调试讲解】基于Spring Boot的考务管理系统设计与实现 085
java·spring boot·后端·spring
東雪木11 小时前
Spring Boot 2.x 集成 Knife4j (OpenAPI 3) 完整操作指南
java·spring boot·后端·swagger·knife4j·java异常处理
陈果然DeepVersion11 小时前
Java大厂面试真题:从Spring Boot到AI微服务的三轮技术拷问(二)
spring boot·redis·spring cloud·微服务·ai·java面试·rag
Q_Q196328847512 小时前
python+django/flask的医院财务管理系统
spring boot·python·django·flask·node.js
半旧夜夏12 小时前
【Gateway】服务调用和网关配置攻略
java·spring boot·spring cloud·gateway