别再用 BeanUtils 了,这款 PO VO DTO 转换神器不香么?

简介: 别再用 BeanUtils 了,这款 PO VO DTO 转换神器不香么?



老铁们是不是经常为写一些实体转换的原始代码感到头疼,尤其是实体字段特别多的时候。介绍一个开源项目 mapstruct ,可以轻松优雅的进行转换,简化你的代码。当然有的人喜欢写get set,或者用BeanUtils 进行复制,代码只是工具,本文只是提供一种思路。

先贴下官网地址吧:https://mapstruct.org/

废话不多说,上代码:

pom 配置:

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <org.mapstruct.version>1.4.1.Final</org.mapstruct.version>
        <org.projectlombok.version>1.18.12</org.projectlombok.version>
</properties>
<dependencies>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>${org.mapstruct.version}</version>
        </dependency>
        <!-- lombok dependencies should not end up on classpath -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${org.projectlombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- idea 2018.1.1 之前的版本需要添加下面的配置,后期的版本就不需要了,可以注释掉,
我自己用的2019.3 -->
     <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-processor</artifactId>
            <version>${org.mapstruct.version}</version>
            <scope>provided</scope>
        </dependency>
</dependencies>
<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>${org.projectlombok.version}</version>
                        </path>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>${org.mapstruct.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
        </plugins>
    </build>

关于lombok和mapstruct的版本兼容问题多说几句,maven插件要使用3.6.0版本以上、lombok使用1.16.16版本以上,另外编译的lombok mapstruct的插件不要忘了加上。否则会出现下面的错误:No property named "aaa" exists in source parameter(s). Did you mean "null"?

这种异常就是lombok编译异常导致缺少get setter方法造成的。还有就是缺少构造函数也会抛异常。

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private String name;
    private int age;
    private GenderEnum gender;
    private Double height;
    private Date birthday;
}
public enum GenderEnum {
    Male("1", "男"),
    Female("0", "女");
    private String code;
    private String name;
    public String getCode() {
        return this.code;
    }
    public String getName() {
        return this.name;
    }
    GenderEnum(String code, String name) {
        this.code = code;
        this.name = name;
    }
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class StudentVO {
    private String name;
    private int age;
    private String gender;
    private Double height;
    private String birthday;
}
@Mapper
public interface StudentMapper {
    StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);
    @Mapping(source = "gender.name", target = "gender")
    @Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
    StudentVO student2StudentVO(Student student);
}

实体类是开发过程少不了的,就算是用工具生成肯定也是要有的,需要手写的部分就是这个Mapper的接口,编译完成后会自动生成相应的实现类

image.png

然后就可以直接用mapper进行实体的转换了

public class Test {
    public static void main(String[] args) {
        Student student = Student.builder().name("小明").age(6).gender(GenderEnum.Male).height(121.1).birthday(new Date()).build();
        System.out.println(student);
        //这行代码便是实际要用的代码
        StudentVO studentVO = StudentMapper.INSTANCE.student2StudentVO(student);
        System.out.println(studentVO);
    }
}

mapper可以进行字段映射,改变字段类型,指定格式化的方式,包括一些日期的默认处理。

可以手动指定格式化的方法:

@Mapper
public interface StudentMapper {
    StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);
    @Mapping(source = "gender", target = "gender")
    @Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
    StudentVO student2StudentVO(Student student);
    default String getGenderName(GenderEnum gender) {
        return gender.getName();
    }
}

上面只是最简单的实体映射处理,下面介绍一些高级用法

1、List 转换

属性映射基于上面的mapping配置

@Mapper
public interface StudentMapper {
    StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);
    @Mapping(source = "gender.name", target = "gender")
    @Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
    StudentVO student2StudentVO(Student student);
    List<StudentVO> students2StudentVOs(List<Student> studentList);
}
public static void main(String[] args) {
    Student student = Student.builder().name("小明").age(6).gender(GenderEnum.Male).height(121.1).birthday(new Date()).build();
    List<Student> list = new ArrayList<>();
    list.add(student);
    List<StudentVO> result = StudentMapper.INSTANCE.students2StudentVOs(list);
    System.out.println(result);
}

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

2、多对象转换到一个对象

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private String name;
    private int age;
    private GenderEnum gender;
    private Double height;
    private Date birthday;
}
@Data
@AllArgsConstructor
@Builder
@NoArgsConstructor
public class Course {
    private String courseName;
    private int sortNo;
    private long id;
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class StudentVO {
    private String name;
    private int age;
    private String gender;
    private Double height;
    private String birthday;
    private String course;
}
@Mapper
public interface StudentMapper {
    StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);
    @Mapping(source = "student.gender.name", target = "gender")
    @Mapping(source = "student.birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
    @Mapping(source = "course.courseName", target = "course")
    StudentVO studentAndCourse2StudentVO(Student student, Course course);
}
public class Test {
    public static void main(String[] args) {
        Student student = Student.builder().name("小明").age(6).gender(GenderEnum.Male).height(121.1).birthday(new Date()).build();
        Course course = Course.builder().id(1L).courseName("语文").build();
        StudentVO studentVO = StudentMapper.INSTANCE.studentAndCourse2StudentVO(student, course);
        System.out.println(studentVO);
    }
}

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

3、默认值

@Mapper
public interface StudentMapper {
    StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);
    @Mapping(source = "student.gender.name", target = "gender")
    @Mapping(source = "student.birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
    @Mapping(source = "course.courseName", target = "course")
    @Mapping(target = "name", source = "student.name", defaultValue = "张三")
    StudentVO studentAndCourse2StudentVO(Student student, Course course);
}



相关文章
|
JSON Java Apache
Bean自动映射工具对比及VO、DTO、PO、DO对象之间的转换
在实际的开发过程中,常常遇到各个层之间对象转换,比如 VO、DTO、PO、DO 等,而如果都是手动set、get,一旦属性较多时,操作起来不仅麻烦,而且浪费时间,因此经常会使用一些工具类,进行对象之间的转换,下面将对象与对象之间转换的方式进行对比,一级对象间的使用进行总结。
Bean自动映射工具对比及VO、DTO、PO、DO对象之间的转换
|
算法 Java 调度
mybatis-plus中的雪花算法
主要介绍mybatis-plus中用到的雪花算法,如有错误或未考虑完全的地方,望不吝赐教。这里默认大家对雪花算法有一定的了解哈
6559 1
mybatis-plus中的雪花算法
|
NoSQL Java MongoDB
Java对MongoDB的ObjectId的序列化问题
MongoDB在不特殊指认的情况下,默认的集合主键是“_id”,类型是ObjectId。ObjectId是一个12字节的BSON类型字符串,包含了UNIX时间戳,机器识别码,进程号,计数值信息。
4685 0
|
IDE 安全 数据管理
Visual Basic for Applications (VBA):自动化Office任务
【4月更文挑战第27天】**Visual Basic for Applications (VBA)** 是Microsoft Office中的宏语言,用于自动化Excel、Word、Outlook等应用的任务。VBA基于Visual Basic,通过编写代码控制应用行为,提升效率。文章介绍了VBA环境、基础语法,展示了在Excel(数据处理)、Word(文档管理)和Outlook(邮件自动化)中的应用。强调安全性和调试重要性,学习VBA能增强Office软件的功能,实现高效自动化工作流程。
466 0
|
移动开发 前端开发 JavaScript
2024年前端框架趋势概览
【10月更文挑战第2天】本文综合了多个来源的信息,以提供一个全面的2024年前端框架趋势概览。希望通过本文,读者能够把握前端开发的最新动态,并在自己的项目中应用这些趋势。
|
XML Java 数据库连接
IDEA如何使mapper直接跳转到xml,超实用
【10月更文挑战第23天】本文介绍了如何在 MyBatis 框架中配置 Mapper 接口和 XML 文件的关联。方法一:使用 MyBatis-Generator 插件自动生成代码;方法二:手动配置,包括命名规范、文件路径设置和 IDEA 设置;此外,还可以通过快捷键、导航栏和 MyBatis-Plugin 插件来增强跳转功能。
5268 1
|
SQL 存储 Java
一文帮你搞定MyBatis的类型转换模块,深度好文,欢迎一键三连!!!
MyBatis是一个持久层框架ORM框架,实现数据库中数据和Java对象中的属性的双向映射,那么不可避免的就会碰到类型转换的问题,在PreparedStatement为SQL语句绑定参数时,需要从Java类型转换为JDBC类型,而从结果集中获取数据时,则需要从JDBC类型转换为Java类型,所以我们来看下在MyBatis中是如何实现类型的转换的。
一文帮你搞定MyBatis的类型转换模块,深度好文,欢迎一键三连!!!
|
消息中间件 搜索推荐 小程序
开源埋点用户行为分析方案-ClickLog埋点(ClkLog)
ClkLog 是一款记录用户行为分析和画像的免费可商用开源软件,技术人员可快速搭建私有的应用系统。项目基于神策分析SDK,采用ClickHouse数据库对采集数据进行存储,采用前后端分离的方式来实现的访问统计和用户画像分析系统。在这里,你可以轻松看到用户访问网页、APP、小程序或业务系统的行为轨迹,同时也可以从时间、地域、渠道、用户访客类型等多维度了解用户的全方位信息,完美助力大数据用户画像、实时归因/离线归因分析、漏斗分析、大数据推荐场景。
1518 2
开源埋点用户行为分析方案-ClickLog埋点(ClkLog)
|
容器
文本溢出省略号text-overflow: ellipsis显示无效?这一属性到底该怎么用?
文本溢出省略号text-overflow: ellipsis显示无效?这一属性到底该怎么用?
484 0
|
机器学习/深度学习 存储 JSON
YOLOv5的Tricks | 【Trick10】从PyTorch Hub加载YOLOv5
YOLOv5的Tricks | 【Trick10】从PyTorch Hub加载YOLOv5
1406 0
YOLOv5的Tricks | 【Trick10】从PyTorch Hub加载YOLOv5