使用 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);
    }


}
相关推荐
追风少年浪子彦6 小时前
mapstruct与lombok冲突原因及解决方案
java·spring boot·spring·spring cloud
军军君016 小时前
基于Springboot+UniApp+Ai实现模拟面试小工具四:后端项目基础框架搭建下
spring boot·spring·面试·elementui·typescript·uni-app·mybatis
白仑色8 小时前
完整 Spring Boot + Vue 登录系统
vue.js·spring boot·后端
MZ_ZXD0018 小时前
flask校园学科竞赛管理系统-计算机毕业设计源码12876
java·spring boot·python·spring·django·flask·php
小郭的学习日记10 小时前
互联网大厂Java面试:从Spring Boot到微服务的场景应用
spring boot·微服务·java面试·技术栈·电商平台
超级小忍10 小时前
在 Spring Boot 中使用 MyBatis 的 XML 文件编写 SQL 语句详解
xml·spring boot·mybatis
Q_Q196328847510 小时前
python的平安驾校管理系统
开发语言·spring boot·python·django·flask·node.js·php
超级小忍11 小时前
在 Spring Boot 中如何使用 Assert 进行断言校验
spring boot·后端
程序猿小D11 小时前
[附源码+数据库+毕业论文+答辩PPT+部署教程+配套软件]基于SpringBoot+MyBatis+MySQL+Maven+Vue实现的交流互动管理系统
spring boot·mysql·vue·mybatis·毕业论文·答辩ppt·交流互动