MapStruct:将数据从一个bean传输到另一个bean

将数据从一种形式转换为另一种形式在IT行业中是一种被高度利用的概念。 MapStruct通过在编译时生成映射器实现,允许基于注释的Bean转换。 这样可以确保在运行时没有性能开销。

什么是MapStruct?

MapStruct是一个代码生成器,它基于约定优于配置的方法大大简化了Java Bean类型之间的映射的实现。

生成的映射代码使用简单的方法调用,因此速度快,类型安全且易于理解。

为什么选择MapStruct?

多层应用程序通常需要在不同的对象模型(例如实体和DTO)之间进行映射。 编写此类映射代码是一项繁琐且容易出错的任务。 MapStruct旨在通过使其尽可能自动化来简化这项工作。

与其他映射框架相比,MapStruct在编译时生成Bean映射,以确保高性能,允许快速的开发人员反馈和彻底的错误检查。

实作

pom.xml

在web.xml中,添加“ maven-compiler-plugin ”,并使用组ID“ org.apache.maven.plugins ”。 您可以添加特定的jdk源/目标版本,并从以下位置获取最新版本
MapStruct网站 。

<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.5.1</version><configuration><source>1.6</source> <!-- or higher, depending on your project --><target>1.6</target> <!-- or higher, depending on your project --><annotationProcessorPaths><path><groupId>org.mapstruct</groupId><artifactId>mapstruct-processor</artifactId><version>1.1.0.Beta1</version></path></annotationProcessorPaths></configuration>
</plugin>

现在添加mapstruct jar作为依赖项。

<dependency><groupId>org.mapstruct</groupId><artifactId>mapstruct</artifactId><version>1.1.0.Beta1</version>
</dependency>

问题陈述与解决方案

假设我们有两个表示个人和业务联系的pojo,如下所述,并且我们都在特定的jsps上使用这两个pojo。 现在,对于两个联系人都相同的功能,我们需要将数据从一种pojo传输到另一种。

PrimaryContact.java

public class PrimaryContact {private String name;private String phone;private String email;public PrimaryContact() {super();}public PrimaryContact(String name, String phone, String email) {super();this.name = name;this.phone = phone;this.email = email;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Overridepublic String toString() {return "PrimaryContact [name=" + name + ", phone=" + phone + ", email=" + email + "]";}}

BusinessContact.java

public class BusinessContact {private String firstName;private String lastName;private String businessPhone;private String businessEmail;private String businessCountry;public BusinessContact() {super();}public BusinessContact(String firstName, String lastName, String businessPhone, String businessEmail,String businessCountry) {super();this.firstName = firstName;this.lastName = lastName;this.businessPhone = businessPhone;this.businessEmail = businessEmail;this.businessCountry = businessCountry;}public String getFirstName() {return firstName;}public void setFirstName(String firstName) {this.firstName = firstName;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public String getBusinessPhone() {return businessPhone;}public void setBusinessPhone(String businessPhone) {this.businessPhone = businessPhone;}public String getBusinessEmail() {return businessEmail;}public void setBusinessEmail(String businessEmail) {this.businessEmail = businessEmail;}public String getBusinessCountry() {return businessCountry;}public void setBusinessCountry(String businessCountry) {this.businessCountry = businessCountry;}@Overridepublic String toString() {return "BusinessContact [firstName=" + firstName + ", lastName=" + lastName + ", businessPhone=" + businessPhone+ ", businessEmail=" + businessEmail + ", businessCountry=" + businessCountry + "]";}}

我们编写一个Mapper来传输数据,如下所示。 注释@Mappings定义了将源pojo中的哪些属性转移到目标pojo中的特定属性。 批注定义@InheritInverseConfiguration反向映射要完成。

ContactMapper.java

/*** @author javareferencegv*/
@Mapper
@DecoratedWith(ContactMapperDecorator.class)
public interface ContactMapper {ContactMapper INSTANCE = Mappers.getMapper(ContactMapper.class);/*** We define only those mappings which doesn't have same signature in source and target*/   @Mappings({ @Mapping(source = "phone", target = "businessPhone"),@Mapping(source = "email", target = "businessEmail"),@Mapping(target = "businessCountry", constant="USA")})BusinessContact primaryToBusinessContact(PrimaryContact primary);@InheritInverseConfigurationPrimaryContact businessToPrimaryContact(BusinessContact business);}

在某些情况下,映射不是直接的,我们需要在将一个属性映射到另一个属性之前使用自定义逻辑。 这里的一个例子是主要联系人有全名,而业务联系人有名和姓。 在这种情况下,我们使用装饰器添加自定义实现。 这是在映射器中添加定义的注释@DecoratedWith。 装饰器的实现如下:

ContactMapperDecorator.java

public abstract class ContactMapperDecorator implements ContactMapper{private final ContactMapper delegate;public ContactMapperDecorator(ContactMapper delegate) {this.delegate = delegate;}@Overridepublic BusinessContact primaryToBusinessContact(PrimaryContact primary){BusinessContact business = delegate.primaryToBusinessContact(primary); //Executes the mapperString[] names = primary.getName().split(" ");business.setFirstName(names[0]);business.setLastName(names[1]);return business;}@Overridepublic PrimaryContact businessToPrimaryContact(BusinessContact business){PrimaryContact primary = delegate.businessToPrimaryContact(business); //Executes the mapperprimary.setName(business.getFirstName() + " " + business.getLastName());return primary;}}

执行方式:

一旦我们构建了一个实现类文件,它将由mapstruct生成。 我们都准备运行映射器。

public class ContactConvertor {public static void main(String[] args) {PrimaryContact primary = new PrimaryContact("Jack Sparrow","9999999999","test@javareferencegv.com");BusinessContact business = ContactMapper.INSTANCE.primaryToBusinessContact(primary);System.out.println(business);PrimaryContact primaryConverted = ContactMapper.INSTANCE.businessToPrimaryContact(business);System.out.println(primaryConverted);}}

输出:

BusinessContact [firstName=Jack, lastName=Sparrow, businessPhone=9999999999, businessEmail=test@javareferencegv.com, businessCountry=USA]
PrimaryContact [name=Jack Sparrow, phone=9999999999, email=test@javareferencegv.com]

翻译自: https://www.javacodegeeks.com/2016/12/mapstruct-transferring-data-one-bean-another.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/351057.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

eclipse发布rest_在Eclipse中高效运行HTTP / REST集成测试

eclipse发布rest最近&#xff0c;我有机会使用由我亲爱的Holger Staudacher编写的OSGi-JAX-RS-Connector库。 通过连接器&#xff0c;您可以通过将Path注释的类型注册为OSGi服务来轻松发布资源-实际上&#xff0c;它工作得很好。 对我来说&#xff0c;使用普通的JUnit测试编写…

gdb调试命令

本文主要参考自&#xff1a;http://www.cnblogs.com/zzx1045917067/archive/2012/12/26/2834310.html&#xff0c;进行了一点补充和编排&#xff1b;Core dump部分参考了&#xff1a;http://blog.ddup.us/?p176。 gdb是一个在UNIX环境下的命令行调试工具。 如果需要使用gdb调试…

分享一个windows下检测硬件信息的bat脚本

文件名必须以.bat结尾&#xff0c;如果出现闪退&#xff0c;请右击鼠标&#xff0c;以管理身份运行即可 echo offcolor 0atitle 硬件检测 mode con cols90sc config winmgmt start auto >nul 2<&1net start winmgmt 2>1nulsetlocal ENABLEDELAYEDEXPANSIONecho 主…

matlab imfinfo返回图像信息

语法&#xff1a; info imfinfo(filename,fmt) %输入图像名&#xff0c;图像的格式 info imfinfo(filename)%输入图像名 示例程序&#xff1a; info imfinfo(C:\test1.jpg) %返回图像信息&#xff0c;注意&#xff1a;输入必须字符串 info.Width …

Apache Camel 2.18发布–包含内容

本周发布了Apache Camel 2.18.0 。 此版本是重要版本&#xff0c;我将在此博客文章中重点介绍。 Java 8 Camel 2.18是要求Java 1.8的第一个发行版&#xff08;例如&#xff0c;容易记住的Camel 2.18 Java1.8。Camel2.17 Java 1.7&#xff09;。 我们采取了谨慎的方法&…

C# 中 FindControl 方法及使用

FindControl 的使用方法 FindControl (String id)&#xff1a; 在页命名容器中搜索带指定标识符的服务器控件。&#xff08;有点类似javascript中的getElementById(string)&#xff09; 今天做了一个打印的报表 &#xff0c;要求在指定位置显示列表中某字段的内容&#xff0c;…

matlab imresize对图像进行缩小放大

matlab中函数imresize简介&#xff1a; 函数功能&#xff1a;该函数用于对图像做缩放处理。 调用格式&#xff1a; B imresize(A, m) 返回的图像B的长宽是图像A的长宽的m倍&#xff0c;即缩放图像。 m大于1&#xff0c; 则放大图像&#xff1b; m小于1&#xff0c; 缩小图像。…

matlab imrotate图像旋转

B imrotate(A,angle) 将图像A&#xff08;图像的数据矩阵&#xff0c;既可以是灰度图像&#xff0c;也可以是RGB图像&#xff09;绕图像的中心点旋转angle度&#xff0c; 正数表示逆时针旋转&#xff0c; 负数表示顺时针旋转。返回旋转后的图像矩阵。 B imrotate(A,angle,met…

理解爬虫原理

1.简单说明爬虫原理 爬虫就是通过互联网各个沾点组成的节点网&#xff0c;通过代码返回给浏览器&#xff0c;然后解析这部分的代内容&#xff0c;将网页内的内容简洁地呈现在我们的面前。爬虫的流程可以分为&#xff1a;发送请求、获取响应内容、解析内容、保存数据。 2.使用 r…

带有Java DSL的Spring Integration MongoDB适配器

1引言 这篇文章解释了如何使用Spring Integration从MongoDB数据库中保存和检索实体。 为了实现这一点&#xff0c;我们将使用Java DSL配置扩展来配置入站和出站MongoDB通道适配器。 例如&#xff0c;我们将构建一个应用程序&#xff0c;使您可以将订单写入MongoDB存储&#xff…

matlab linspace

用法&#xff1a;linspace(x1,x2,N)   功能&#xff1a;linspace是Matlab中的一个指令&#xff0c;用于产生x1,x2之间的N点行矢量。其中x1、x2、N分别为起始值、中止值、元素个数。若缺省N&#xff0c;默认点数为100。在matlab的命令窗口下输入help linspace或者doc linspac…

Linux strace命令

简介 strace常用来跟踪进程执行时的系统调用和所接收的信号。 在Linux世界&#xff0c;进程不能直接访问硬件设备&#xff0c;当进程需要访问硬件设备(比如读取磁盘文件&#xff0c;接收网络数据等等)时&#xff0c;必须由用户态模式切换至内核态模式&#xff0c;通 过系统调用…

网站发布

1.文件发布 右击工程&#xff0c;选择发布 发布方法选择文件发布&#xff0c;打开你的程式路径&#xff0c;然后一步步操作即可。 转载于:https://www.cnblogs.com/alannxu/p/10613453.html

什么是javax.ws.rs.core.context? [第4部分]

如何使用Context批注 在什么是javax.ws.rs.core.context的第3部分中&#xff1f; 您学习了如何在请求和配置&#xff0c;提供程序和应用程序实例中使用Context批注。 在本文中&#xff0c;您将学习如何使用Context批注注入HttpServletResponse和HttpServletRequest类。 获取对…

matlab im2double

im2double函数&#xff0c;如果输入是 uint8 unit16 或者是二值的logical类型&#xff0c;则函数im2double 将其值归一化到0&#xff5e;1之间。

重学前端(一)

前端知识框架&#xff1a;自己觉得很不错的一个前端知识框架 转载于:https://www.cnblogs.com/angel1254/p/10616065.html

couchbase_Couchbase:使用Twitter和Java创建大型数据集

couchbase在播放/演示Couchbase或任何其他NoSQL引擎时&#xff0c;创建大型数据集的一种简单方法是将Twitter feed注入数据库。 对于这个小应用程序&#xff0c;我正在使用&#xff1a; Couchbase Server 2.0服务器 Couchbase Java SDK &#xff08;将由Maven安装&#xff0…

C编译器、链接器、加载器详解

一、概述 C语言的编译链接过程要把我们编写的一个c程序&#xff08;源代码&#xff09;转换成可以在硬件上运行的程序&#xff08;可执行代码&#xff09;&#xff0c;需要进行编译和链接。编译就是把文本形式源代码翻译为机器语言形式的目标文件的过程。链接是把目标文件、操作…

matlab bwdist

bwdist函数用于计算元素之间的距离。 举个例子&#xff1a; 如果a 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 0 那么&#xff1a; [D,L]bwdist(a); D 1.4142 1.0000 1.0000 1.0000 1.4142 1.0000 0 0 0 1.0000 1.0000 0 0 0 1.0000 1.0000 0 0 0 1.0000 1.4142 1.000…

js函数库-D3

推荐&#xff1a; https://www.cnblogs.com/createGod/p/6884629.html转载于:https://www.cnblogs.com/john-hwd/p/10616166.html