【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

原文地址:https://www.cnblogs.com/huashengweilong/p/11379372.html