iis服务器助手广告
返回顶部
首页 > 资讯 > 精选 >Spring BeanUtils如何忽略空值拷贝
  • 385
分享到

Spring BeanUtils如何忽略空值拷贝

2023-06-29 13:06:55 385人浏览 八月长安
摘要

这篇文章主要讲解了“spring BeanUtils如何忽略空值拷贝”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring BeanUtils如何忽略空值拷贝”吧!B

这篇文章主要讲解了“spring BeanUtils如何忽略空值拷贝”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring 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;@Datapublic 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;@Datapublic 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;@RestControllerpublic 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如何忽略空值拷贝这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

    --结束END--

    本文标题: Spring BeanUtils如何忽略空值拷贝

    本文链接: https://www.lsjlt.com/news/325089.html(转载时请注明来源链接)

    有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

    本篇文章演示代码以及资料文档资料下载

    下载Word文档到电脑,方便收藏和打印~

    下载Word文档
    猜你喜欢
    • Spring BeanUtils如何忽略空值拷贝
      这篇文章主要讲解了“Spring BeanUtils如何忽略空值拷贝”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring BeanUtils如何忽略空值拷贝”吧!B...
      99+
      2023-06-29
    • SpringBeanUtils忽略空值拷贝的方法示例代码
      目录简介获取null属性名(工具类)示例工具类EntityController测试 其他文件其他网址简介 说明 本文用示例介绍Spring(SpringBoot)如何使用B...
      99+
      2024-04-02
    • BeanUtils.copyProperties在拷贝属性时忽略空值的操作
      BeanUtils.copyProperties忽略空值 使用spring开发的人,对这行代码肯定不陌生,常用于DTO、VO、PO之间的复制。 BeanUtils.copyPr...
      99+
      2024-04-02
    • 如何解析Python中的赋值、浅拷贝和深拷贝
      这篇文章给大家介绍如何解析Python中的赋值、浅拷贝和深拷贝,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。先明确几点不可变类型:该数据类型对象所指定内存中的值不可以被改变。(1)、在改变某个对象的值时,由于其内存中的...
      99+
      2023-06-22
    • golang如何忽略函数返回值?
      在 go 语言中,可使用下划线标识符 _ 忽略函数返回值:_ 表示忽略第一个返回值。指定变量名捕获后续返回值(例如错误处理)。当明确不需要返回值时才建议忽略它们。 Go 语言中忽略函数...
      99+
      2024-04-23
      golang 忽略函数返回值
    • c语言scanf返回值被忽略如何解决
      当scanf函数的返回值被忽略,可能会导致程序出现错误或不按预期工作。为了解决这个问题,可以采取以下几种方法:1. 检查scanf函...
      99+
      2023-10-09
      c语言
    • 我们如何忽略 MySQL DATEDIFF() 函数返回的负值
      要忽略 MySQL DATEDIFF() 函数返回的负值,您可以使用ABS()函数来获取日期之间的绝对差值。以下是一个示例查询,演示...
      99+
      2023-10-20
      MySQL
    • 我们如何忽略 MySQL DATEDIFF() 函数返回的负值?
      众所周知,DATEDIFF() 函数用于获取两个日期之间的天数差。因此,它也很可能返回负值。mysql> select * from differ; +------------+-------------+ | OrderD...
      99+
      2023-10-22
    • 如何进行python列表中的赋值与深浅拷贝
      今天就跟大家聊聊有关如何进行python列表中的赋值与深浅拷贝,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。  首先创建一个列表  a=[[1,2,...
      99+
      2024-04-02
    • 使用numpy对数组求平均时如何忽略nan值
      目录numpy对数组求平均时忽略nan值使用np.mean()的效果使用np.nanmean()的效果numpy含nan值进行归一化操作方法一方法二numpy对数组求平均时忽略nan...
      99+
      2024-04-02
    • linux下scp远程拷贝包含空格的目录或者文件的问题如何解决
      本篇内容介绍了“linux下scp远程拷贝包含空格的目录或者文件的问题如何解决”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!描述: 今天需要...
      99+
      2023-06-13
    软考高级职称资格查询
    编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
    • 官方手机版

    • 微信公众号

    • 商务合作