Spring BeanUtils忽略空值拷贝的方法示例代码

目录
  • 简介
  • 获取null属性名(工具类)
  • 示例
    • 工具类
    • Entity
    • Controller
    • 测试
    • 其他文件
  • 其他网址

简介

说明

本文用示例介绍Spring(SpringBoot)如何使用BeanUtils拷贝对象属性(忽略空值)。

BeanUtils类所在的包

有两个包都提供了BeanUtils类:

Spring的(推荐):org.springframework.beans.BeanUtilsApache的:org.apache.commons.beanutils.BeanUtils

忽略null值拷贝属性的用法

BeanUtils.copyProperties(Object source, Object target, String... ignoreProperties)

获取null属性名(工具类)

可以自己写一个工具类,用来获取对象里所有null的属性名字。

package com.example.util;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;
public class PropertyUtil {
    public static String[] getNullPropertyNames(Object source) {
        BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            //check if value of this property is null then add it to the collection
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null){
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}

示例

本处为了全面,将以下几种情况都考虑进去:

  • 继承了某个类
  • 某个属性是个Entity

工具类

package com.example.util;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;
public class PropertyUtil {
    public static String[] getNullPropertyNames(Object source) {
        BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            //check if value of this property is null then add it to the collection
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null){
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}

Entity

基础Entity

package com.example.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class BaseEntity {
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
    private Long deletedFlag;
}

User

package com.example.entity;

import lombok.Data;
@Data
public class User {
    private Long id;
    private String userName;
    private String nickName;
    // 0:正常 1:被锁定
    private Integer status;
}

Blog

package com.example.entity;

import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
public class Blog extends BaseEntity{
    private Long id;
    private String title;
    private String content;
    private User user;
}

VO

package com.example.vo;

import com.example.entity.BaseEntity;
import com.example.entity.User;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
public class BlogRequest extends BaseEntity {
    private Long id;
    private String title;
    private String content;
    private User user;
}

Controller

package com.example.controller;

import com.example.entity.Blog;
import com.example.entity.User;
import com.example.util.PropertyUtil;
import com.example.vo.BlogRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.Arrays;
@RestController
public class HelloController {
    @Autowired
    private ObjectMapper objectMapper;
    @GetMapping("/test")
    public String test() {
        BlogRequest blogRequest = new BlogRequest();
        blogRequest.setId(10L);
        blogRequest.setTitle("Java实战");
        // blogRequest.setContent("本文介绍获取null的字段名的方法");
        blogRequest.setUser(new User());
        blogRequest.setCreateTime(LocalDateTime.now());
        // blogRequest.setCreateTime(LocalDateTime.now());
        blogRequest.setDeletedFlag(0L);
        User user = new User();
        user.setId(15L);
        user.setUserName("Tony");
        // user.setNickName("Iron Man");
        // user.setStatus(1);
        String[] nullPropertyNames = PropertyUtil.getNullPropertyNames(blogRequest);
        System.out.println(Arrays.toString(nullPropertyNames));
        System.out.println("------------------------------");
        Blog blog = new Blog();
        BeanUtils.copyProperties(blogRequest, blog, nullPropertyNames);
        try {
            System.out.println(objectMapper.writeValueAsString(blog));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "test success";
    }
}

测试

访问:http://localhost:8080/test/

后端结果:

[updateTime, content]
------------------------------
{"createTime":"2022-03-17 19:58:32","updateTime":null,"deletedFlag":0,"id":10,"title":"Java实战","content":null,"user":{"id":null,"userName":null,"nickName":null,"status":null}}

结论

  • 可以获取父类的null的属性名
  • 不可以获取属性的null的属性名

其他文件

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo_SpringBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo_SpringBoot</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0.RELEASE</version>
            </plugin>
        </plugins>
    </build>

</project>

其他网址

Spring BeanUtils忽略空值拷贝用法 - 掘金

到此这篇关于Spring BeanUtils忽略空值拷贝的方法示例代码的文章就介绍到这了,更多相关Spring BeanUtils忽略空值拷贝内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 浅析Java中Apache BeanUtils和Spring BeanUtils的用法

    # 前言 在我们实际项目开发过程中,我们经常需要将不同的两个对象实例进行属性复制,从而基于源对象的属性信息进行后续操作,而不改变源对象的属性信息,比如DTO数据传输对象和数据对象DO,我们需要将DO对象进行属性复制到DTO,但是对象格式又不一样,所以我们需要编写映射代码将对象中的属性值从一种类型转换成另一种类型. # 对象拷贝 在具体介绍两种 BeanUtils 之前,先来补充一些基础知识.它们两种工具本质上就是对象拷贝工具,而对象拷贝又分为深拷贝和浅拷贝,下面进行详细解释. # 什么是浅拷贝和

  • JSP 开发之Spring BeanUtils组件使用

    JSP 开发之Spring BeanUtils组件使用 用于演示的javabean import java.util.Date; public class People { private String name; private int age; private Date birth; public People(String name, int age, Date birth) { super(); this.name = name; this.age = age; this.birth =

  • 基于Spring BeanUtils的copyProperties方法使用及注意事项

    如下所示: package com.demo; import lombok.Data; import org.springframework.beans.BeanUtils; import java.util.Arrays; import java.util.List; /** * @author xiaobu * @version JDK1.8.0_171 * @date on 2019/10/8 10:04 * @description */ public class BeanUtilsTe

  • Spring BeanUtils忽略空值拷贝的方法示例代码

    目录 简介 获取null属性名(工具类) 示例 工具类 Entity Controller 测试 其他文件 其他网址 简介 说明 本文用示例介绍Spring(SpringBoot)如何使用BeanUtils拷贝对象属性(忽略空值). BeanUtils类所在的包 有两个包都提供了BeanUtils类: Spring的(推荐):org.springframework.beans.BeanUtilsApache的:org.apache.commons.beanutils.BeanUtils 忽略nu

  • Java spring boot 实现支付宝支付功能的示例代码

    一.准备工作: 1.登陆支付宝开发者中心,申请一个开发者账号. 地址:https://openhome.alipay.com/ 2.进入研发服务: 3.点击链接进入工具下载页面: 4.点击下载对应版本的RSA公钥生成器: 5.生成公钥密钥(记录你的应用私钥): 6.在支付宝配置公钥(点击保存): 二.搭建demo 1.引入jia包: <dependency> <groupId>com.alipay.sdk</groupId> <artifactId>alip

  • Python实现删除某列中含有空值的行的示例代码

    客户需求 查看销售人员不为空值的行 数据存储情况如图: 代码实现 import pandas as pd data = pd.read_excel('test.xlsx',sheet_name='Sheet1') datanota = data[data['销售人员'].notna()] print(datanota) 输出结果 D:\Python\Anaconda\python.exe D:/Python/test/EASdeal/test.py 城市 销售金额 销售人员 0 北京 10000

  • Java调用微信支付功能的方法示例代码

    Java 使用微信支付 前言百度搜了一下微信支付,都描述的不太好,于是乎打算自己写一个案例,希望以后拿来直接改造使用. 因为涉及二维码的前端显示,所以有前端的内容 一. 准备工作 所需微信公众号信息配置 APPID:绑定支付的APPID(必须配置) MCHID:商户号(必须配置) KEY:商户支付密钥,参考开户邮件设置(必须配置) APPSECRET:公众帐号secert(仅JSAPI支付的时候需要配置) 我这个案例用的是尚硅谷一位老师提供的,这里不方便提供出来,需要大家自己找,或者公司提供 二

  • Oracle查看表结构的几种方法示例代码

    1,DESCRIBE 命令 使用方法如下: SQL> describe nchar_tst(nchar_tst为表名) 显示的结果如下: 名称 是否为空? 类型 ----------------------------------------- -------- ---------------------------- NAME NCHAR(6) ADDR NVARCHAR2(16) SAL NUMBER(9,2) 2,DBMS_METADATA.GET_DDL包 使用方法如下: SQL> S

  • Spring Boot 实现Restful webservice服务端示例代码

    1.Spring Boot configurations application.yml spring: profiles: active: dev mvc: favicon: enabled: false datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/wit_neptune?createDatabaseIfNotExist=true&useUnicode=true&

  • Java 添加Word目录的2种方法示例代码详解

    目录是一种能够快速.有效地帮助读者了解文档或书籍主要内容的方式.在Word中,插入目录首先需要设置相应段落的大纲级别,根据大纲级别来生成目录表.本文中生成目录分2种情况来进行: 1.文档没有设置大纲级别,生成目录前需要手动设置 2.文档已设置大纲级别,通过域代码生成目录 使用工具: •Free Spire.Doc for Java 2.0.0 (免费版) •IntelliJ IDEA 工具获取途径1:通过官网下载jar文件包,解压并导入jar文件到IDEA程序. 工具获取途径2:通过Maven仓

  • C++解密Chrome80版本数据库的方法示例代码

    谷歌浏览器Google Chrome 80正式版例行更新详细版本80.0.3987.163.Google Chrome浏览器又称谷歌浏览器采用Chromium内核全球最受欢迎的免费网页浏览器追求速度.隐私安全的网络浏览器. 先说下吧.chrome80以前的版本是直接可以通过DPAPI来进行解密的.关于DPAPI 大家可以 看这里的介绍 DPAPI是Windows系统级对数据进行加解密的一种接口无需自实现加解密代码微软已经提供了经过验证的高质量加解密算法提供了用户态的接口对密钥的推导存储数据加解密

  • Spring Boot加密配置文件特殊内容的示例代码详解

    有时安全不得不考虑,看看新闻泄漏风波事件就知道了我们在用Spring boot进行开发时,经常要配置很多外置参数ftp.数据库连接信息.支付信息等敏感隐私信息,如下 ​ 这不太好,特别是互联网应用,应该用加密的方式比较安全,有点类似一些应用如电商.公安.安检平台.滚动式大屏中奖信息等显示身份证号和手机号都是前几位4109128*********和158*******.那就把图中的明文改造下1. 引入加密包,可选,要是自己实现加解密算法,就不需要引入第三方加解密库 <dependency> &l

  • 基于Java的MathML转图片的方法(示例代码)

    Maven依赖: <dependency> <groupId>de.rototor.jeuclid</groupId> <artifactId>jeuclid-core</artifactId> <version>3.1.14</version> </dependency> 示例: @Test public void testMathMlToImg() throws IOException { //MathML

随机推荐