zoukankan      html  css  js  c++  java
  • 【Java】【50】BeanUtils.copyProperties();只从源对象中拷贝自己为null的值

    前言:

    关联博客:

    【Java】【3】BeanUtils.copyProperties();将一个实体类的值复制到另外一个实体类 - 花生喂龙 - 博客园
    https://www.cnblogs.com/huashengweilong/p/10690509.html

    关联博客里的是最简单的两个实体类赋值的情况,将oldEntity的值,赋给newEntity。而项目中有时的要求是,newEntity里的对应字段有值,就用newEntity里的;没有值,才将oldEntity的值赋给newEntity。

    正文:

    用法:

    BeanUtil.copyProperties(oldObject, newObject, true, CopyOptions.create().setXXXX(true))

    参数:

    editable:限制的类或接口,必须为目标对象的实现接口或父类,用于限制拷贝的属性,例如一个类我只想复制其父类的一些属性,就可以将editable设置为父类。
    ignoreNullValue:是否忽略空值,当源对象的值为null时,true: 忽略而不注入此值,false: 注入null
    ignoreProperties:忽略的属性列表,设置一个属性列表,不拷贝这些属性值
    ignoreError:是否忽略字段注入错误
    可以通过CopyOptions.create()方法创建一个默认的配置项,通过setXXX方法设置每个配置项

    当前需求的写法:

    BeanUtil.copyProperties(oldDetail.get(), userDetail, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));

    pom.xml

    //这是别人写的jar包,他的文档:http://hutool.mydoc.io/#text_319433 
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>4.1.14</version>
    </dependency>

    代码

    public Entity test(Entity inputEntity){
        Entity newEntity = new Entity();
        Entity oldEntity = this.dao...; //从数据库获取
        if (oldDetail.isPresent()) {
            BeanUtil.copyProperties(oldEntity.get(), inputEntity, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        }
        BeanUtil.copyProperties(inputEntity, newEntity);
        return newEntity;
    }

    参考博客:

    BeanUtils.copyProperties忽略null值/只拷贝非null属性 - ★【World Of Moshow 郑锴】★ - CSDN博客
    https://blog.csdn.net/moshowgame/article/details/82826535

  • 相关阅读:
    Android编译选项eng、user、userdebug的区别
    Linux 内核编码规范
    PLM之EVT、DVT、PVT、MP
    fastboot刷机的一般方法
    Android手机拨号测试项
    使用Genymotion安装APK出现错误INSTALL_FAILED_CPU_ABI_INCOMPATIBLE的解决办法
    三星手机列表拖动时出现诡异背景色的问题
    分享android ADT百度云盘下载地址
    关于互联网思维
    分享Nginx在Windows下的管理命令(bat文件)
  • 原文地址:https://www.cnblogs.com/huashengweilong/p/11379372.html
Copyright © 2011-2022 走看看