作者:bettermann

toutiao.com/i6891531055631696395/

老铁们是不是经常为写一些实体转换的原始代码感到头疼,尤其是实体字段特别多的时候。介绍一个开源项目 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的接口,编译完成后会自动生成相应的实现类

然后就可以直接用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);
}

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);}}

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);}

一款PO VO DTO 转换神器,求求你别在到处找工具类了!相关推荐

  1. 一款 PO VO DTO 转换神器

    欢迎关注方志朋的博客,回复"666"获面试宝典 老铁们是不是经常为写一些实体转换的原始代码感到头疼,尤其是实体字段特别多的时候.介绍一个开源项目 mapstruct ,可以轻松优雅 ...

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

    欢迎关注方志朋的博客,回复"666"获面试宝典 来源:toutiao.com/i6891531055631696395 老铁们是不是经常为写一些实体转换的原始代码感到头疼,尤其是实 ...

  3. PO VO DTO 转换神器替代BeanUtils 了

    PO VO DTO 1. MapStruct简介 2.0 MapStruct入门 2.0.1 简易demo 2.1. 引入依赖 2.2. 需要转换的对象 2.3. 创建转换器 2.4. 验证 2.5. ...

  4. 【工具神器】PO VO DTO 转换神器

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

  5. 一款自动写文案的神器——西瓜树元引擎智能文案工具

    你是不是还在为写不出短视频文案而发愁呢?今天给大家分享一款自动写文案的神器--西瓜树元引擎智能文案工具,文案自动生成写作辅助工具,以后文案写作.素材寻找,都不愁了. 我们只需提出一个主题或关键词,西瓜 ...

  6. VO的实际应用;后端接收前端传入的值;实体类转化VO;PO,VO,DTO,BO,DAO,POJO区别

    文章目录 各层转换流程 分层领域模型规约: 领域模型命名规约: 后端向前端传参 封装 前端向后台传参 封装 快速转换解决方案 参考 各层转换流程 分层领域模型规约: DO( Data Object): ...

  7. Java 中的PO VO DTO BO

    PO 持久对象,数据: BO 业务对象,封装对象.复杂对象 ,里面可能包含多个类: DTO 传输对象,前端调用时传输 : VO 表现对象,前端界面展示. 当你业务足够简单时,一个POJO 也完全当做P ...

  8. POJO,PO,VO,DTO

    1.POJO POJO(Plain Ordinary Java Object)简单的Java对象,实际就是普通JavaBeans,是为了避免和EJB混淆所创造的简称. POJO (Plain Old ...

  9. Java开发中的几种对象的说明(PO,VO,DTO,BO,POJO,DAO,SAO等)

    一.PO :(persistant object ),持久对象 可以看成是与数据库中的表相映射的java对象,也就是说只有属性和setter和getter方法.使用Hibernate来生成PO是不错的 ...

  10. PO VO DTO BO区别及用法

    PO: persistant object持久对象 最形象的理解就是一个PO就是数据库中的一条记录. 好处是可以把一条记录作为一个对象处理,可以方便的转为其它对象. BO: businessobjec ...

最新文章

  1. This application is modifying the autolayout engine
  2. cmd中添加中文字体
  3. python set使用
  4. python的进程模块
  5. 12c oracle 修改内存_关于Oracle数据库12c 新特性总结
  6. android strm,Android 关于so文件的随记
  7. 禁用任何未使用的端口com_CentOS7 - 使用Fail2ban保护SSH
  8. python r转义_Python快速入门系列之二:还学不会我直播跪搓衣板
  9. 做训练营需要具备什么样必备条件?
  10. [小笔记]TypeScript/JavaScript模拟Python中的Range函数
  11. 【LeetCode】【字符串】题号:*520. 检测大写字母
  12. c语言范式编程之lsearch
  13. 角色扮演RPG游戏项目
  14. 十年磨一剑——一夜成名背后是十年的努力
  15. Python:求列表的最大数以及下标
  16. CSS3无限滚动(无线循环滚动)
  17. 基于Android的sina微博分享功能
  18. 用php求两数之和,Leetcode PHP 两数之和
  19. 希望之花计算机音乐,希望之花 - 寒逸原创 - 5SING中国原创音乐基地
  20. Java并发编程实战(学习笔记十 第十一章 性能与可伸缩性)

热门文章

  1. java 伪造http请求ip地址
  2. 部署AIX nmon监控脚本
  3. angular4学习记录 -- 依赖注入
  4. 利用Docker快速部署Oracle环境
  5. SqlServer 在创建数据库时候指定的初始数据库大小是不能被收缩的
  6. 学习微软企业库存心得--总结
  7. 普通二本,去了小公司,我也想改变
  8. poj 3020 Antenna Placement 匈牙利二分匹配 最小覆盖数 !!!!
  9. 如何让 Mac 加入网络帐户服务器?
  10. 在 Mac 上的 Keynote 中如何先排版再选照片?