BeanUtils.copyProperties忽略null值/只拷贝非null属性

问题场景

例如有个对象要提交,提交一次,第二次提交我们希望是对上次提交的完善。。那么用其他方式实现很麻烦,本身的BeanUtils.copyProperties也是不大支持。

2020-12-19更新 新增了更好用的BeanMerge方法,可以直接完整的copy对象属性,把两个属性合成到一个上面,详情请参考 《比BeanCopy好用的BeanMerge(java合并对象属性,把非空属性合成到目标对象上)》

解决方案

hutool开源库为我们提供了更为强大的Bean工具-BeanUtil,

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>4.1.14</version>
</dependency>

以上问题,只需要一句代码就搞定!!!

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

核心代码是CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true)

详情可以参考官方文档 http://hutool.mydoc.io/#text_319433 。

更详细的业务场景如下:

public Object save(UserDetail userDetail){
        if(userDetail.getUserId()==0){
            return ApiReturnUtil.error("userId不能为空");
        }else{
        	//复制一个新的用于保存
         	UserDetail newDetail=new UserDetail();
            BeanUtil.copyProperties(userDetail,newDetail);
            Optional<UserDetail> oldDetail=userDetailRepository.findById(userDetail.getUserId());
            if (oldDetail.isPresent()){
                System.out.println("copying");
                //复制旧的属性过来,忽略null属性,忽略null值,有值的以新的为主,null的则以旧为主
                BeanUtil.copyProperties(oldDetail.get(),userDetail,true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            }
            //复制新的所有非null来覆盖旧的
            BeanUtil.copyProperties(userDetail,newDetail,true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));

            userDetailRepository.save(newDetail);
            return  ApiReturnUtil.success("保存成功",newDetail);
        }
    }

CopyOptions配置项:

CopyOptions参数提供一些BeanUtils.copyProperties注入属性的选项。

使用方法如下:
BeanUtil.copyProperties(oldObject,newObject,true, CopyOptions.create().setXXXX(true));

  • editable 限制的类或接口,必须为目标对象的实现接口或父类,用于限制拷贝的属性,例如一个类我只想复制其父类的一些属性,就可以将editable设置为父类。
  • ignoreNullValue 是否忽略空值,当源对象的值为null时,true: 忽略而不注入此值,false: 注入null
  • ignoreProperties 忽略的属性列表,设置一个属性列表,不拷贝这些属性值
  • ignoreError 是否忽略字段注入错误
    可以通过CopyOptions.create()方法创建一个默认的配置项,通过setXXX方法设置每个配置项。
BeanUtils.copyProperties方法可以用于对象之间的属性拷贝,但默认情况下它会将源对象的所有属性拷贝到目标对象中,包括null。如果需要忽略源对象中的null属性,可以使用BeanUtils.copyProperties方法的第三个参数,即属性过滤器。 属性过滤器是一个实现了org.springframework.be.BeanUtils.CopyablePropertyFilter接口的对象,它可以控制哪些属性需要被拷贝。在属性过滤器的accept方法中,可以根据属性是否为null来决定是否拷贝属性。 以下是一个示例代码,演示了如何使用BeanUtils.copyProperties方法忽略null: ```java import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.CopyablePropertyFilter; public class CopyPropertiesExample { public static void main(String[] args) { SourceObject source = new SourceObject(); source.setName("John"); source.setAge(25); source.setAddress(null); TargetObject target = new TargetObject(); BeanUtils.copyProperties(source, target, (sourceValue, targetValue, targetPropertyDescriptor) -> { // 忽略源对象中的null属性 return sourceValue != null; }); System.out.println(target.getName()); // 输出:John System.out.println(target.getAge()); // 输出:25 System.out.println(target.getAddress()); // 输出:null } } class SourceObject { private String name; private int age; private String address; // 省略getter和setter方法 } class TargetObject { private String name; private int age; private String address; // 省略getter和setter方法 } ``` 在上述示例中,我们创建了一个SourceObject对象,并设置了name、age和address属性,其中address属性null。然后我们创建了一个TargetObject对象,并使用BeanUtils.copyProperties方法将SourceObject的属性拷贝到TargetObject中,通过属性过滤器忽略了源对象中的null属性。最后我们输出了TargetObject对象的属性,可以看到address属性null
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值