Mapstruct 简明教程

MapStruct - Quick Guide

MapStruct - Overview

MapStruct 是一个插入 Java 编译器的注释处理器。一旦插入,就可以通过 maven、gradle 等命令行工具使用它来处理映射注释,并在编译时创建映射器类。

MapStruct is an annotation processor which is plugged into Java Compiler. Once plugged in, it can be used by command line tools like maven, gradle to process the mapping annotation to create a mapper class at compile time.

When Mapping is required?

在多层应用程序中,数据对象用于从数据库提取数据,而 UI 与模型交互。现在,需要将提取到数据模型中的数据映射到要传递给 UI 的模型或 Java bean 中。考虑以下情况。

In multilayered applications, data objects are used to fetch data from database and UI interacts with Models. Now data fetched into data models is required to map to Model or java beans to be passed to UI.Consider the following case.

与数据库相连的实体类。

Entity class connected with database.

StudentEntity.java

@Entity
class StudentEntity {
   String id;
   String name;
}

与 UI 相连的模型类。

Model class connected with UI.

Student.java

class Student {
   String id;
   String name;
}

How MapStruct Works?

MapStruct 自动化使用注释将数据对象与模型对象进行映射的映射器创建过程。它在编译时创建映射器实现,这有助于开发人员在开发期间找出错误并便于理解。比如 −

MapStruct automates the process of creating a mapper to map data objects with model objects using annotations. It creates a mapper implementation at compile time which helps developer to figure out error during development and make is easy to understand. For example −

StudentMapper.java

@Mapper
class StudentMapper {
   StudentMapper INSTANCE = Mappers.getMapper( StudentMapper.class );
   StudentEntity modelToEntity(Student student);
}

现在,可以使用 StudentMapper.INSTANCE 轻松获取映射对象。

Now StudentMapper.INSTANCE can be used to get mapped objects easily.

StudentEntity studentEntity = StudentMapper.INSTANCE.modelToEntity(student);

MapStruct - Environment Setup

MapStruct 是一个基于 Java 的库,因此第一个要求是在你的机器上安装 JDK。

MapStruct is a Java based library, so the very first requirement is to have JDK installed on your machine.

Step 1 - Setup Java Development Kit (JDK)

你可以从 Oracle 的 Java 站点下载 SDK 的最新版本 − Java SE Downloads. 你在下载文件中可以找到安装 JDK 的说明,按照给定的说明进行安装和配置。最后设置 PATH 和 JAVA_HOME 环境变量以引用包含 java 和 javac 的目录,通常分别为 java_install_dir/bin 和 java_install_dir。

You can download the latest version of SDK from Oracle’s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

如果你运行的是 Windows,并且已在 C:\jdk-9.0.1 中安装了 JDK,你必须在你的 C:\autoexec.bat 文件中输入以下行。

If you are running Windows and have installed the JDK in C:\jdk-9.0.1, you would have to put the following line in your C:\autoexec.bat file.

set PATH=C:\jdk-11.0.11\bin;%PATH%
set JAVA_HOME=C:\jdk-11.0.11

或者,在 Windows NT/2000/XP 中,你必须右键单击我的电脑,选择属性 → 高级 → 环境变量。然后,你将不得不更新 PATH 值并单击确定按钮。

Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.

在 Unix(Solaris、Linux 等)上,如果 SDK 安装在 /usr/local/jdk-9.0.1 中并且你使用 C shell,你将必须输入以下内容到你的 .cshrc 文件中。

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-9.0.1 and you use the C shell, you will have to put the following into your .cshrc file.

setenv PATH /usr/local/jdk-11.0.11/bin:$PATH
setenv JAVA_HOME /usr/local/jdk-11.0.11

或者,如果你使用诸如 Borland JBuilder、Eclipse、IntelliJ IDEA 或 Sun ONE Studio 这样的集成开发环境 (IDE),则必须编译并运行一个简单程序来确认 IDE 知道你在何处安装了 Java。否则,你必须按照 IDE 文档中给出的内容执行正确的设置。

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.

Step 2 - Install mapstruct library along with dependencies

MVNRepository 下载以下 jar,并在你的类路径中使用它们。

Download following jars from MVNRepository and use them in your classpath.

  1. mapstruct-1.5.0.Beta1.jar

  2. mapstruct-processor-1.5.0.Beta1.jar

确保正确设置此目录上的 CLASSPATH 变量,否则在运行应用程序时会遇到问题。

Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application.

Step 3 - Setup Eclipse IDE

本教程中的所有示例都是使用 Eclipse IDE 编写的。因此,我们建议你应该在你机器上安装 Eclipse 的最新版本。

All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine.

要安装 Eclipse IDE,请从 www.eclipse.org/downloads 下载最新的 Eclipse 二进制文件。下载安装文件后,将二进制分发包解压到方便的位置。例如,在 Windows 上的 C:\eclipse 中,或 Linux/Unix 上的 /usr/local/eclipse 中,最后相应地设置 PATH 变量。

To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately.

可以通过在 Windows 机器上执行以下命令启动 Eclipse,或者你只需双击 eclipse.exe

Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe

%C:\eclipse\eclipse.exe

可以通过在 Unix(Solaris、Linux 等)机器上执行以下命令启动 Eclipse −

Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −

$/usr/local/eclipse/eclipse

成功启动后,如果一切正常,它应该显示以下结果 −

After a successful startup, if everything is fine then it should display the following result −

eclipsehomepage

Step 4 - Create a Maven Project

C:\MVN>mvn archetype:generate
-DgroupId = com.tutorialspoint.mapping
-DartifactId = mapping
-DarchetypeArtifactId = maven-archetype-quickstart
-DinteractiveMode = false

它将创建一个 maven 项目。现在,按如下方式更新 pom.xml 文件 −

It will create a maven project. Now update the pom.xml file as follows −

<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 http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.tutorialspoint.mapping</groupId>
   <artifactId>mapping</artifactId>
   <packaging>jar</packaging>
   <version>1.0-SNAPSHOT</version>
   <name>mapping</name>
   <url>http://maven.apache.org</url>
   <dependencies>
      <dependency>
         <groupId>org.junit.jupiter</groupId>
         <artifactId>junit-jupiter-engine</artifactId>
         <version>5.0.0</version>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.mapstruct</groupId>
         <artifactId>mapstruct</artifactId>
         <version>1.5.0.Beta1</version>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
               <source>11</source>
               <target>11</target>
               <annotationProcessorPaths>
                  <path>
                     <groupId>org.mapstruct</groupId>
                     <artifactId>mapstruct-processor</artifactId>
                     <version>1.5.0.Beta1</version>
                  </path>
               </annotationProcessorPaths>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

运行以下命令以更新 maven 依赖关系并构建项目。

Run the following command to update maven dependencies and build project.

mvn package

一旦命令成功。将基于 maven 的项目作为 maven 项目导入到 Eclipse。其余的 Eclipse 将处理。

Once command is successful. Import the maven based project in Eclipse as a maven project. Rest Eclipse will handle.

MapStruct - Basic Mapping

使用 Mapstruct 非常简单。要创建映射器,请在接口上使用 org.mapstruct.Mapper 注释。

Using mapstruct is very easy. To create a mapper use org.mapstruct.Mapper annotation on an interface.

@Mapper
public interface StudentMapper {...}

现在在接口中创建一个转换方法。

Now create a conversion method in interface.

@Mapper
public interface StudentMapper {
   Student getModelFromEntity(StudentEntity student);
}

如果源和目标对象属性拥有相同名称,则会自动映射那些属性。如果属性名称不同,则请按照以下方式使用 @Mapping 注释 −

In case both source and target object properties have same name, those properties will be mapped automatically. In case property name is different, use the @Mapping annotation as following −

@Mapper
public interface StudentMapper {
   @Mapping(target="className", source="classVal")
   Student getModelFromEntity(StudentEntity student);
}

此处,className 是 Student 中的属性名称,a 目标对象和 classVal 是 StudentEntity 中的属性名称,a 源对象。

Here className is the property name in Student, a target object and classVal is the property name in StudentEntity, a source object.

Example

在 Eclipse 中将项目映射打开为 Environment Setup 章中创建的内容。

Open project mapping as created in Environment Setup chapter in Eclipse.

使用以下代码创建 Student.java−

Create Student.java with following code −

Student.java

package com.tutorialspoint.model;

public class Student {
   private int id;
   private String name;
   private String className;

   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getClassName() {
      return className;
   }
   public void setClassName(String className) {
      this.className = className;
   }
}

使用以下代码创建 Student.java−

Create Student.java with following code −

StudentEntity.java

package com.tutorialspoint.entity;

public class StudentEntity {
   private int id;
   private String name;
   private String classVal;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getClassVal() {
      return classVal;
   }
   public void setClassVal(String classVal) {
      this.classVal = classVal;
   }
}

使用以下代码创建 StudentMapper.java −

Create StudentMapper.java with following code −

StudentMapper.java

package com.tutorialspoint.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.model.Student;

@Mapper
public interface StudentMapper {

   @Mapping(target="className", source="classVal")
   Student getModelFromEntity(StudentEntity student);

   @Mapping(target="classVal", source="className")
   StudentEntity getEntityFromModel(Student student);
}

使用以下代码创建 StudentMapperTest.java −

Create StudentMapperTest.java with following code −

StudentMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;

public class StudentMapperTest {

   private StudentMapper studentMapper
      = Mappers.getMapper(StudentMapper.class);

   @Test
   public void testEntityToModel() {
      StudentEntity entity = new StudentEntity();
      entity.setClassVal("X");
      entity.setName("John");
      entity.setId(1);

      Student model = studentMapper.getModelFromEntity(entity);

      assertEquals(entity.getClassVal(), model.getClassName());
      assertEquals(entity.getName(), model.getName());
      assertEquals(entity.getId(), model.getId());
   }

   @Test
   public void testModelToEntity() {
      Student model = new Student();
      model.setId(1);
      model.setName("John");
      model.setClassName("X");

      StudentEntity entity = studentMapper.getEntityFromModel(model);

      assertEquals(entity.getClassVal(), model.getClassName());
      assertEquals(entity.getName(), model.getName());
      assertEquals(entity.getId(), model.getId());
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec
...

MapStruct - Custom Mapping

我们还可以向使用 org.mapstruct.Mapper 注释创建的映射器中添加自定义方法。我们可以创建抽象类,而不是接口。Mapstruct 自动创建相应的映射器类。

We can add custom methods as well to the Mapper created using org.mapstruct.Mapper annotation. We can create abstract class as well intead of an Interface. Mapstruct automatically creates the corresponding mapper class.

现在,在接口中创建一个默认转换方法。

Now create a default conversion method in interface.

@Mapper
public interface StudentMapper {
   default Student getModelFromEntity(StudentEntity studentEntity){
      Student student = new Student();
      student.setId(studentEntity.getId());
      student.setName(studentEntity.getName());
      student.setClassName(studentEntity.getClassVal());
      return student;
   }
}

以类似的方式,我们可以创建一个抽象类以及映射器。

In similar fashion, we can create an abstract class as well as a mapper.

@Mapper
public absgract class StudentMapper {
   Student getModelFromEntity(StudentEntity studentEntity){
      Student student = new Student();
      student.setId(studentEntity.getId());
      student.setName(studentEntity.getName());
      student.setClassName(studentEntity.getClassVal());
      return student;
   }
}

Example

在 Eclipse 中打开在第 Environment Setup 章中创建的媒体播放器项目。

Open project mediaPlayer as created in Environment Setup chapter in Eclipse.

使用以下代码创建 Student.java−

Create Student.java with following code −

Student.java

package com.tutorialspoint.model;

public class Student {
   private int id;
   private String name;
   private String className;

   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getClassName() {
      return className;
   }
   public void setClassName(String className) {
      this.className = className;
   }
}

使用以下代码创建 Student.java−

Create Student.java with following code −

StudentEntity.java

package com.tutorialspoint.entity;

public class StudentEntity {
   private int id;
   private String name;
   private String classVal;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getClassVal() {
      return classVal;
   }
   public void setClassVal(String classVal) {
      this.classVal = classVal;
   }
}

使用以下代码创建 StudentMapper.java −

Create StudentMapper.java with following code −

StudentMapper.java

package com.tutorialspoint.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.model.Student;

@Mapper
public interface StudentMapper {

   default Student getModelFromEntity(StudentEntity studentEntity){
      Student student = new Student();
      student.setId(studentEntity.getId());
      student.setName(studentEntity.getName());
      student.setClassName(studentEntity.getClassVal());
      return student;
   }

   @Mapping(target="classVal", source="className")
   StudentEntity getEntityFromModel(Student student);
}

使用以下代码创建 StudentMapperTest.java −

Create StudentMapperTest.java with following code −

StudentMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;

public class StudentMapperTest {

   private StudentMapper studentMapper
      = Mappers.getMapper(StudentMapper.class);

   @Test
   public void testEntityToModel() {
      StudentEntity entity = new StudentEntity();
      entity.setClassVal("X");
      entity.setName("John");
      entity.setId(1);

      Student model = studentMapper.getModelFromEntity(entity);

      assertEquals(entity.getClassVal(), model.getClassName());
      assertEquals(entity.getName(), model.getName());
      assertEquals(entity.getId(), model.getId());
   }

   @Test
   public void testModelToEntity() {
      Student model = new Student();
      model.setId(1);
      model.setName("John");
      model.setClassName("X");

      StudentEntity entity = studentMapper.getEntityFromModel(model);

      assertEquals(entity.getClassVal(), model.getClassName());
      assertEquals(entity.getName(), model.getName());
      assertEquals(entity.getId(), model.getId());
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec
...

MapStruct - Mapping Multiple Objects

我们还可以添加多个对象的映射。例如,我们要获取使用 Student 和 Address 对象的 DeliveryAddress 对象。

We can add map multiple objects as well. For Example, we want to get a DeliveryAddress Object using Student and Address object.

现在创建可将两个对象映射到一个对象的映射器界面。

Now create a mapper interface which can map two objects into one.

@Mapper
public interface DeliveryAddressMapper {
   @Mapping(source = "student.name", target = "name")
   @Mapping(source = "address.houseNo", target = "houseNumber")
   DeliveryAddress getDeliveryAddress(StudentEntity student, AddressEntity address);
}

Example

在 Eclipse 中打开在第 Custom Mapping 章中更新的映射项目。

Open project mapping as updated in Custom Mapping chapter in Eclipse.

使用以下代码创建 DeliveryAddress.java −

Create DeliveryAddress.java with following code −

DeliveryAddress.java

package com.tutorialspoint.model;

public class DeliveryAddress {
	private String name;
	private int houseNumber;
	private String city;
	private String state;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getHouseNumber() {
		return houseNumber;
	}
	public void setHouseNumber(int houseNumber) {
		this.houseNumber = houseNumber;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
}

使用以下代码创建 AddressEntity.java −

Create AddressEntity.java with following code −

AddressEntity.java

package com.tutorialspoint.entity;

public class AddressEntity {
	private int houseNo;
	private String city;
	private String state;
	public int getHouseNo() {
		return houseNo;
	}
	public void setHouseNo(int houseNo) {
		this.houseNo = houseNo;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
}

使用以下代码创建 DeliveryAddressMapper.java −

Create DeliveryAddressMapper.java with following code −

DeliveryAddressMapper.java

package com.tutorialspoint.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import com.tutorialspoint.entity.AddressEntity;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.model.DeliveryAddress;

@Mapper
public interface DeliveryAddressMapper {
   @Mapping(source = "student.name", target = "name")
   @Mapping(source = "address.houseNo", target = "houseNumber")
   DeliveryAddress getDeliveryAddress(StudentEntity student, AddressEntity address);
}

使用以下代码创建 DeliveryAddressMapperTest.java −

Create DeliveryAddressMapperTest.java with following code −

DeliveryAddressMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.AddressEntity;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.mapper.DeliveryAddressMapper;
import com.tutorialspoint.model.DeliveryAddress;

public class DeliveryAddressMapperTest {

   private DeliveryAddressMapper deliveryAddressMapper
      = Mappers.getMapper(DeliveryAddressMapper.class);

   @Test
   public void testEntityToModel() {
      StudentEntity student = new StudentEntity();
      student.setClassVal("X");
      student.setName("John");
      student.setId(1);

      AddressEntity address = new AddressEntity();
      address.setCity("Y");
      address.setState("Z");
      address.setHouseNo(1);

      DeliveryAddress deliveryAddress = deliveryAddressMapper.getDeliveryAddress(student, address);

      assertEquals(deliveryAddress.getName(), student.getName());
      assertEquals(deliveryAddress.getCity(), address.getCity());
      assertEquals(deliveryAddress.getState(), address.getState());
      assertEquals(deliveryAddress.getHouseNumber(), address.getHouseNo());

   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.011 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Mapping Nested Bean

MapStruct 处理嵌套映射似乎很无缝。例如,一个有主题作为嵌套 Bean 的学生。

MapStruct handles nested mapping seemlessly. For example, a Student with Subject as nested bean.

现在创建一个可以映射嵌套对象的映射器接口。

Now create a mapper interface which can map nested objects.

@Mapper
public interface StudentMapper {
   @Mapping(target="className", source="classVal")
   @Mapping(target="subject", source="subject.name")
   Student getModelFromEntity(StudentEntity studentEntity);

   @Mapping(target="classVal", source="className")
   @Mapping(target="subject.name", source="subject")
   StudentEntity getEntityFromModel(Student student);
}

Example

在Eclipse中打开在 Mapping Multiple Objects 章节中更新的项目映射。

Open project mapping as updated in Mapping Multiple Objects chapter in Eclipse.

使用以下代码创建 SubjectEntity.java −

Create SubjectEntity.java with following code −

SubjectEntity.java

package com.tutorialspoint.entity;

public class SubjectEntity {
   private String name;
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}

使用以下代码更新 StudentEntity.java −

Update StudentEntity.java with following code −

StudentEntity.java

package com.tutorialspoint.entity;

public class StudentEntity {
   private int id;
   private String name;
   private String classVal;
   private SubjectEntity subject;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getClassVal() {
      return classVal;
   }
   public void setClassVal(String classVal) {
      this.classVal = classVal;
   }
   public SubjectEntity getSubject() {
      return subject;
   }
   public void setSubject(SubjectEntity subject) {
      this.subject = subject;
   }
}

使用以下代码更新 Student.java −

Update Student.java with following code −

Student.java

package com.tutorialspoint.model;

public class Student {
   private int id;
   private String name;
   private String className;
   private String subject;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getClassName() {
      return className;
   }
   public void setClassName(String className) {
      this.className = className;
   }
   public String getSubject() {
      return subject;
   }
   public void setSubject(String subject) {
      this.subject = subject;
   }
}

使用以下代码更新 StudentMapper.java −

Update StudentMapper.java with following code −

StudentMapper.java

package com.tutorialspoint.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.model.Student;

@Mapper
public interface StudentMapper {

   @Mapping(target="className", source="classVal")
   @Mapping(target="subject", source="subject.name")
   Student getModelFromEntity(StudentEntity studentEntity);

   @Mapping(target="classVal", source="className")
   @Mapping(target="subject.name", source="subject")
   StudentEntity getEntityFromModel(Student student);
}

使用以下代码更新 StudentMapperTest.java −

Update StudentMapperTest.java with following code −

StudentMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.entity.SubjectEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;

public class StudentMapperTest {
   private StudentMapper studentMapper
      = Mappers.getMapper(StudentMapper.class);

   @Test
   public void testEntityToModel() {
      StudentEntity entity = new StudentEntity();
      entity.setClassVal("X");
      entity.setName("John");
      entity.setId(1);

      SubjectEntity subject = new SubjectEntity();
      subject.setName("Computer");
      entity.setSubject(subject);

      Student model = studentMapper.getModelFromEntity(entity);

      assertEquals(entity.getClassVal(), model.getClassName());
      assertEquals(entity.getName(), model.getName());
      assertEquals(entity.getId(), model.getId());
      assertEquals(entity.getSubject().getName(), model.getSubject());
   }

   @Test
   public void testModelToEntity() {
      Student model = new Student();
      model.setId(1);
      model.setName("John");
      model.setClassName("X");
      model.setSubject("Science");
      StudentEntity entity = studentMapper.getEntityFromModel(model);

      assertEquals(entity.getClassVal(), model.getClassName());
      assertEquals(entity.getName(), model.getName());
      assertEquals(entity.getId(), model.getId());
      assertEquals(entity.getSubject().getName(), model.getSubject());
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec

Results :

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Mapping Direct Fields

MapStruct 轻松处理直接字段映射。例如,一个带有私有属性的 Student 和一个带有公共属性的 StudentEntity。为了同时进行 getter/setter 映射,属性应为公共属性。如果为 public final,那么只会有一个 getter 方法用于映射。

MapStruct handles direct fields mapping easily. For example, a Student with section as private property and StudentEntity with section as public property. To have both getter/setter mapping, a property should be public. In case of public final, only getter method will be present for mapping.

现在,创建一个映射器接口。我们将使用 @InheritInverseConfiguration 注释来复制反向配置。

Now create a mapper interface. We’ll use @InheritInverseConfiguration annotation to copy reverse configuration now.

@Mapper
public interface StudentMapper {
   @Mapping(target="className", source="classVal")
   @Mapping(target="subject", source="subject.name")
   Student getModelFromEntity(StudentEntity studentEntity);

   @InheritInverseConfiguration
   StudentEntity getEntityFromModel(Student student);
}

Example

在 Eclipse 中将项目映射打开为 Mapping Nested Objects 章中更新的内容。

Open project mapping as updated in Mapping Nested Objects chapter in Eclipse.

使用以下代码更新 StudentEntity.java −

Update StudentEntity.java with following code −

StudentEntity.java

package com.tutorialspoint.entity;

public class StudentEntity {
   private int id;
   private String name;
   private String classVal;
   private SubjectEntity subject;
   public String section;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getClassVal() {
      return classVal;
   }
   public void setClassVal(String classVal) {
      this.classVal = classVal;
   }
   public SubjectEntity getSubject() {
      return subject;
   }
   public void setSubject(SubjectEntity subject) {
      this.subject = subject;
   }
}

使用以下代码更新 Student.java −

Update Student.java with following code −

Student.java

package com.tutorialspoint.model;

public class Student {
   private int id;
   private String name;
   private String className;
   private String subject;
   private String section;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getClassName() {
      return className;
   }
   public void setClassName(String className) {
      this.className = className;
   }
   public String getSubject() {
      return subject;
   }
   public void setSubject(String subject) {
      this.subject = subject;
   }
   public String getSection() {
      return section;
   }
   public void setSection(String section) {
      this.section = section;
   }
}

使用以下代码更新 StudentMapper.java −

Update StudentMapper.java with following code −

StudentMapper.java

package com.tutorialspoint.mapper;

import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.model.Student;

@Mapper
public interface StudentMapper {

   @Mapping(target="className", source="classVal")
   @Mapping(target="subject", source="subject.name")
   Student getModelFromEntity(StudentEntity studentEntity);

   @InheritInverseConfiguration
   StudentEntity getEntityFromModel(Student student);
}

使用以下代码更新 StudentMapperTest.java −

Update StudentMapperTest.java with following code −

StudentMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.entity.SubjectEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;

public class StudentMapperTest {
   private StudentMapper studentMapper
      = Mappers.getMapper(StudentMapper.class);

   @Test
   public void testEntityToModel() {
      StudentEntity entity = new StudentEntity();
      entity.setClassVal("X");
      entity.setName("John");
      entity.setId(1);
      entity.section = "A";
      SubjectEntity subject = new SubjectEntity();
      subject.setName("Computer");
      entity.setSubject(subject);

      Student model = studentMapper.getModelFromEntity(entity);

      assertEquals(entity.getClassVal(), model.getClassName());
      assertEquals(entity.getName(), model.getName());
      assertEquals(entity.getId(), model.getId());
      assertEquals(entity.getSubject().getName(), model.getSubject());
      assertEquals(entity.section, model.getSection());
   }

   @Test
   public void testModelToEntity() {
      Student model = new Student();
      model.setId(1);
      model.setName("John");
      model.setClassName("X");
      model.setSubject("Science");
      model.setSection("A");
      StudentEntity entity = studentMapper.getEntityFromModel(model);

      assertEquals(entity.getClassVal(), model.getClassName());
      assertEquals(entity.getName(), model.getName());
      assertEquals(entity.getId(), model.getId());
      assertEquals(entity.getSubject().getName(), model.getSubject());
      assertEquals(entity.section, model.getSection());
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec

Results :

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Using Builder

MapStruct 允许使用 Builder。我们可以使用 Builder 框架或可以自定义 Builder。在以下示例中,我们使用自定义 Builder。

MapStruct allows to use Builders. We can use Builder frameworks or can use our custom builder. In below example, we are using a custom builder.

Example

在 Eclipse 中打开项目映射为 Mapping Direct Fields 中的更新内容。

Open project mapping as updated in Mapping Direct Fields chapter in Eclipse.

使用以下代码更新 Student.java −

Update Student.java with following code −

Student.java

package com.tutorialspoint.model;

public class Student {
   private final String name;
   private final int id;

   protected Student(Student.Builder builder) {
      this.name = builder.name;
      this.id = builder.id;
   }
   public static Student.Builder builder() {
      return new Student.Builder();
   }
   public static class Builder {
      private String name;
      private int id;
      public Builder name(String name) {
         this.name = name;
         return this;
      }
      public Builder id(int id) {
         this.id = id;
         return this;
      }
      public Student create() {
         return new Student( this );
      }
   }
   public String getName() {
      return name;
   }
   public int getId() {
      return id;
   }
}

使用以下代码更新 StudentMapper.java −

Update StudentMapper.java with following code −

StudentMapper.java

package com.tutorialspoint.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.model.Student;

@Mapper
public interface StudentMapper {
   Student getModelFromEntity(StudentEntity studentEntity);
   @Mapping(target="id", source="id")
   @Mapping(target="name", source="name")
   StudentEntity getEntityFromModel(Student student);
}

使用以下代码更新 StudentMapperTest.java −

Update StudentMapperTest.java with following code −

StudentMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.entity.SubjectEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;

public class StudentMapperTest {
   private StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);

   @Test
   public void testEntityToModel() {
      StudentEntity entity = new StudentEntity();
      entity.setName("John");
      entity.setId(1);
      Student model = studentMapper.getModelFromEntity(entity);
      assertEquals(entity.getName(), model.getName());
      assertEquals(entity.getId(), model.getId());
   }
   @Test
   public void testModelToEntity() {
      Student.Builder builder = Student.builder().id(1).name("John");
      Student model = builder.create();
      StudentEntity entity = studentMapper.getEntityFromModel(model);
      assertEquals(entity.getName(), model.getName());
      assertEquals(entity.getId(), model.getId());
   }
}

运行以下命令以测试映射。

Run the following command to test the mappings.

mvn clean test

Output

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec

Results :

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Implicit Type Conversion

在大多数情况下,MapStruct 自动处理类型转换。例如,int 到 Long 或 String 转换。转换也处理 null 值。以下是部分重要自动转换:

MapStruct handles conversion of type conversions automatically in most of the cases. For example, int to Long or String conversion. Conversion handles null values as well. Following are the some of the important automatic conversions.

  1. Between primitive types and Corresponding Wrapper Classes.

  2. Between primitive types and String.

  3. Between enum types and String.

  4. Between BigInt, BigDecimal and String.

  5. Between Calendar/Date and XMLGregorianCalendar.

  6. Between XMLGregorianCalendar and String.

  7. Between Jodas date types and String.

Example

在 Eclipse 中打开在第 Mapping Using Builder 章中更新后的项目映射。

Open project mapping as updated in Mapping Using Builder chapter in Eclipse.

使用以下代码更新 StudentEntity.java −

Update StudentEntity.java with following code −

StudentEntity.java

package com.tutorialspoint.entity;

public class StudentEntity {
   private String id;
   private String name;
   private String classVal;
   private SubjectEntity subject;
   public String section;
   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getClassVal() {
      return classVal;
   }
   public void setClassVal(String classVal) {
      this.classVal = classVal;
   }
   public SubjectEntity getSubject() {
      return subject;
   }
   public void setSubject(SubjectEntity subject) {
      this.subject = subject;
   }
}

Student.java 未更改,内容如下:

Student.java is unchanged with following code −

Student.java

package com.tutorialspoint.model;

public class Student {
   private final String name;
   private final int id;

   protected Student(Student.Builder builder) {
      this.name = builder.name;
      this.id = builder.id;
   }

   public static Student.Builder builder() {
      return new Student.Builder();
   }

   public static class Builder {
      private String name;
      private int id;

      public Builder name(String name) {
         this.name = name;
         return this;
      }

      public Builder id(int id) {
         this.id = id;
         return this;
      }

      public Student create() {
         return new Student( this );
      }
   }

   public String getName() {
      return name;
   }

   public int getId() {
      ret+urn id;
   }
}

使用以下代码更新 DeliveryAddressMapperTest.java:

Update DeliveryAddressMapperTest.java with following code −

DeliveryAddressMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.AddressEntity;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.mapper.DeliveryAddressMapper;
import com.tutorialspoint.model.DeliveryAddress;

public class DeliveryAddressMapperTest {

   private DeliveryAddressMapper deliveryAddressMapper
      = Mappers.getMapper(DeliveryAddressMapper.class);

   @Test
   public void testEntityToModel() {
      StudentEntity student = new StudentEntity();
      student.setClassVal("X");
      student.setName("John");
      student.setId("1");

      AddressEntity address = new AddressEntity();
      address.setCity("Y");
      address.setState("Z");
      address.setHouseNo(1);

      DeliveryAddress deliveryAddress = deliveryAddressMapper.getDeliveryAddress(student, address);

      assertEquals(deliveryAddress.getName(), student.getName());
      assertEquals(deliveryAddress.getCity(), address.getCity());
      assertEquals(deliveryAddress.getState(), address.getState());
      assertEquals(deliveryAddress.getHouseNumber(), address.getHouseNo());

   }
}

使用以下代码更新 StudentMapperTest.java −

Update StudentMapperTest.java with following code −

StudentMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.entity.SubjectEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;

public class StudentMapperTest {

   private StudentMapper studentMapper
      = Mappers.getMapper(StudentMapper.class);

   @Test
   public void testEntityToModel() {
      StudentEntity entity = new StudentEntity();
      entity.setName("John");
      entity.setId("1");

      Student model = studentMapper.getModelFromEntity(entity);
      assertEquals(entity.getName(), model.getName());
      assertEquals(Integer.parseInt(entity.getId()), model.getId());
   }

   @Test
   public void testModelToEntity() {
      Student.Builder builder = Student.builder().id(1).name("John");
      Student model = builder.create();
      StudentEntity entity = studentMapper.getEntityFromModel(model);

      assertEquals(entity.getName(), model.getName());
      assertEquals(Integer.parseInt(entity.getId()), model.getId());
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec

Results :

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Using numberFormat

MapStruct 可以无缝地处理数字到字符串的转换。我们可以在 @Mapping 注解期间将所需格式作为数字格式传递。例如,考虑以下情况,存储在数字中的金额将以货币格式显示。

MapStruct handles conversion of numbers to String in required format seamlessly. We can pass the required format as numberFormat during @Mapping annotation. For example, consider a case where an amount stored in numbers is to be shown in currency format.

  1. Source - Entity has price as 350.

  2. Target - Model to show price as $350.00.

  3. numberFormat - Use format $#.00

Example

在 Eclipse 中打开在第 Mapping Implicit Type Conversions 章中更新后的项目映射。

Open project mapping as updated in Mapping Implicit Type Conversions chapter in Eclipse.

使用以下代码创建 CarEntity.java:

Create CarEntity.java with following code −

CarEntity.java

package com.tutorialspoint.entity;

public class CarEntity {
   private int id;
   private double price;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public double getPrice() {
      return price;
   }
   public void setPrice(double price) {
      this.price = price;
   }
}

使用以下代码创建 Car.java:

Create Car.java with following code −

Car.java

package com.tutorialspoint.model;

public class Car {
   private int id;
   private String price;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getPrice() {
      return price;
   }
   public void setPrice(String price) {
      this.price = price;
   }
}

使用以下代码创建 CarMapper.java:

Create CarMapper.java with following code −

CarMapper.java

package com.tutorialspoint.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;

@Mapper
public interface CarMapper {
   @Mapping(source = "price", target = "price", numberFormat = "$#.00")
   Car getModelFromEntity(CarEntity carEntity);
}

使用以下代码创建 CarMapperTest.java:

Create CarMapperTest.java with following code −

CarMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;

public class CarMapperTest {
   private CarMapper carMapper
      = Mappers.getMapper(CarMapper.class);

   @Test
   public void testEntityToModel() {
      CarEntity entity = new CarEntity();
      entity.setPrice(345000);
      entity.setId(1);

      Car model = carMapper.getModelFromEntity(entity);
      assertEquals(model.getPrice(), "$345000.00");
      assertEquals(entity.getId(), model.getId());
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Using dateFormat

MapStruct 可以无缝地处理日期到字符串的转换。我们可以在 @Mapping 注解期间将所需格式作为日期格式传递。例如,考虑以下情况,存储在数字中的日期将以特定格式显示。

MapStruct handles conversion of date to String in required format seamlessly. We can pass the required format as dateFormat during @Mapping annotation. For example, consider a case where a date stored in numbers is to be shown in particular format.

  1. Source - Entity has date as GregorianCalendar(2015, 3, 5).

  2. Target - Model to show date as 05.04.2015.

  3. dateFormat - Use format dd.MM.yyyy

Example

在 Eclipse 中打开在第 Mapping Using numberFormat 章中更新后的项目映射。

Open project mapping as updated in Mapping Using numberFormat chapter in Eclipse.

使用以下代码更新 CarEntity.java −

Update CarEntity.java with following code −

CarEntity.java

package com.tutorialspoint.entity;
import java.util.GregorianCalendar;

public class CarEntity {
   private int id;
   private double price;
   private GregorianCalendar manufacturingDate;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public double getPrice() {
      return price;
   }
   public void setPrice(double price) {
      this.price = price;
   }
   public GregorianCalendar getManufacturingDate() {
      return manufacturingDate;
   }
   public void setManufacturingDate(GregorianCalendar manufacturingDate) {
      this.manufacturingDate = manufacturingDate;
   }
}

使用以下代码更新 Car.java −

Update Car.java with following code −

Car.java

package com.tutorialspoint.model;

public class Car {
   private int id;
   private String price;
   private String manufacturingDate;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getPrice() {
      return price;
   }
   public void setPrice(String price) {
      this.price = price;
   }
   public String getManufacturingDate() {
      return manufacturingDate;
   }
   public void setManufacturingDate(String manufacturingDate) {
      this.manufacturingDate = manufacturingDate;
   }
}

使用以下代码更新 CarMapper.java −

Update CarMapper.java with following code −

CarMapper.java

package com.tutorialspoint.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;

@Mapper
public interface CarMapper {
   @Mapping(source = "price", target = "price", numberFormat = "$#.00")
   @Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy")
   Car getModelFromEntity(CarEntity carEntity);
}

使用以下代码更新 CarMapperTest.java −

Update CarMapperTest.java with following code −

CarMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.GregorianCalendar;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;

public class CarMapperTest {
   private CarMapper carMapper
      = Mappers.getMapper(CarMapper.class);

   @Test
   public void testEntityToModel() {
      CarEntity entity = new CarEntity();
      entity.setPrice(345000);
      entity.setId(1);
      entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));
      Car model = carMapper.getModelFromEntity(entity);
      assertEquals(model.getPrice(), "$345000.00");
      assertEquals(entity.getId(), model.getId());
      assertEquals("05.04.2015", model.getManufacturingDate());
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Using expression

MapStruct 允许调用转换方法,用于定制逻辑。我们可以使用表达式来实现相同目的,其中我们可以传递任何 java 对象并调用其方法来执行转换。

MapStruct allows to call a conversion method for customized logic. We can use expression to achieve the same where we can pass any java object and call its method to do the conversion.

Syntax

@Mapping(target = "target-property",
	expression = "java(target-method())")

此处:

Here

  1. target-property - the property for which we are doing the mapping.

  2. expression - mapper will call the java method written in the expression.

  3. target-method - target-method is the method to be called. In case method is present in different class, use new class-name.target-method()

Example

在 Eclipse 中打开更新的 Mapping Using dateFormat 章节中的项目映射。

Open project mapping as updated in Mapping Using dateFormat chapter in Eclipse.

使用以下代码更新 CarEntity.java −

Update CarEntity.java with following code −

CarEntity.java

package com.tutorialspoint.entity;
import java.util.GregorianCalendar;

public class CarEntity {
   private int id;
   private double price;
   private GregorianCalendar manufacturingDate;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public double getPrice() {
      return price;
   }
   public void setPrice(double price) {
      this.price = price;
   }
   public GregorianCalendar getManufacturingDate() {
      return manufacturingDate;
   }
   public void setManufacturingDate(GregorianCalendar manufacturingDate) {
      this.manufacturingDate = manufacturingDate;
   }
}

使用以下代码更新 Car.java −

Update Car.java with following code −

Car.java

package com.tutorialspoint.model;

public class Car {
   private int id;
   private String price;
   private String manufacturingDate;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getPrice() {
      return price;
   }
   public void setPrice(String price) {
      this.price = price;
   }
   public String getManufacturingDate() {
      return manufacturingDate;
   }
   public void setManufacturingDate(String manufacturingDate) {
      this.manufacturingDate = manufacturingDate;
   }
}

使用以下代码更新 CarMapper.java −

Update CarMapper.java with following code −

CarMapper.java

package com.tutorialspoint.mapper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;

@Mapper
public interface CarMapper {
   @Mapping(source = "price", target = "price", numberFormat = "$#.00")
   @Mapping(target = "manufacturingDate",
      expression = "java(getManufacturingDate(carEntity.getManufacturingDate()))")
   Car getModelFromEntity(CarEntity carEntity);

   default String getManufacturingDate(GregorianCalendar manufacturingDate) {
      Date d = manufacturingDate.getTime();
      SimpleDateFormat sdf = new SimpleDateFormat( "dd.MM.yyyy" );
      return sdf.format( d );
   }
}

使用以下代码更新 CarMapperTest.java −

Update CarMapperTest.java with following code −

CarMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.GregorianCalendar;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;

public class CarMapperTest {
   private CarMapper carMapper
      = Mappers.getMapper(CarMapper.class);

   @Test
   public void testEntityToModel() {
      CarEntity entity = new CarEntity();
      entity.setPrice(345000);
      entity.setId(1);
      entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));
      Car model = carMapper.getModelFromEntity(entity);
      assertEquals(model.getPrice(), "$345000.00");
      assertEquals(entity.getId(), model.getId());
      assertEquals("05.04.2015", model.getManufacturingDate());
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Using constant

MapStruct 允许将常数值映射到属性。

MapStruct allows to map a constant value to a property.

Syntax

@Mapping(target = "target-property", const = "const-value")

此处:

Here

  1. target-property - the property for which we are doing the mapping.

  2. const-value - mapper will map the const-value to target-property.

以下示例演示了相同内容。

Following example demonstrates the same.

Example

在 Eclipse 中打开更新的 Mapping Using dateFormat 章节中的项目映射。

Open project mapping as updated in Mapping Using dateFormat chapter in Eclipse.

使用以下代码更新 CarEntity.java −

Update CarEntity.java with following code −

CarEntity.java

package com.tutorialspoint.entity;
import java.util.GregorianCalendar;

public class CarEntity {
   private int id;
   private double price;
   private GregorianCalendar manufacturingDate;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public double getPrice() {
      return price;
   }
   public void setPrice(double price) {
      this.price = price;
   }
   public GregorianCalendar getManufacturingDate() {
      return manufacturingDate;
   }
   public void setManufacturingDate(GregorianCalendar manufacturingDate) {
      this.manufacturingDate = manufacturingDate;
   }
}

使用以下代码更新 Car.java −

Update Car.java with following code −

Car.java

package com.tutorialspoint.model;

public class Car {
   private int id;
   private String price;
   private String manufacturingDate;
   private String brand;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getPrice() {
      return price;
   }
   public void setPrice(String price) {
      this.price = price;
   }
   public String getManufacturingDate() {
      return manufacturingDate;
   }
   public void setManufacturingDate(String manufacturingDate) {
      this.manufacturingDate = manufacturingDate;
   }
   public String getBrand() {
      return brand;
   }
   public void setBrand(String brand) {
      this.brand = brand;
   }
}

使用以下代码更新 CarMapper.java −

Update CarMapper.java with following code −

CarMapper.java

package com.tutorialspoint.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;

@Mapper
public interface CarMapper {
   @Mapping(target = "brand", constant = "BMW")
   @Mapping(source = "price", target = "price", numberFormat = "$#.00")
   @Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy")
   Car getModelFromEntity(CarEntity carEntity);
}

使用以下代码更新 CarMapperTest.java −

Update CarMapperTest.java with following code −

CarMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.GregorianCalendar;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;

public class CarMapperTest {
   private CarMapper carMapper
      = Mappers.getMapper(CarMapper.class);

   @Test
   public void testEntityToModel() {
      CarEntity entity = new CarEntity();
      entity.setPrice(345000);
      entity.setId(1);
      entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));
      Car model = carMapper.getModelFromEntity(entity);
      assertEquals(model.getPrice(), "$345000.00");
      assertEquals(entity.getId(), model.getId());
      assertEquals("05.04.2015", model.getManufacturingDate());
      assertEquals("BMW", model.getBrand());
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Using defaultValue

使用 Mapstruct,我们可以使用 @Mapping 注解的 defaultValue 属性在源属性为 null 的情况下传递默认值。

Using Mapstruct we can pass the default value in case source property is null using defaultValue attribute of @Mapping annotation.

Syntax

@Mapping(target = "target-property", source="source-property"
defaultValue = "default-value")

此处:

Here

  1. default-value - target-property will be set as default-value in case source-property is null.

以下示例演示了相同内容。

Following example demonstrates the same.

Example

在 Eclipse 中打开映射,在 Mapping Using Constant 章节中更新。

Open project mapping as updated in Mapping Using Constant chapter in Eclipse.

使用以下代码更新 CarEntity.java −

Update CarEntity.java with following code −

CarEntity.java

package com.tutorialspoint.entity;
import java.util.GregorianCalendar;

public class CarEntity {
   private int id;
   private double price;
   private GregorianCalendar manufacturingDate;
   private String name;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public double getPrice() {
      return price;
   }
   public void setPrice(double price) {
      this.price = price;
   }
   public GregorianCalendar getManufacturingDate() {
      return manufacturingDate;
   }
   public void setManufacturingDate(GregorianCalendar manufacturingDate) {
      this.manufacturingDate = manufacturingDate;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

使用以下代码更新 Car.java −

Update Car.java with following code −

Car.java

package com.tutorialspoint.model;

public class Car {
   private int id;
   private String price;
   private String manufacturingDate;
   private String brand;
   private String name;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getPrice() {
      return price;
   }
   public void setPrice(String price) {
      this.price = price;
   }
   public String getManufacturingDate() {
      return manufacturingDate;
   }
   public void setManufacturingDate(String manufacturingDate) {
      this.manufacturingDate = manufacturingDate;
   }
   public String getBrand() {
      return brand;
   }
   public void setBrand(String brand) {
      this.brand = brand;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

使用以下代码更新 CarMapper.java −

Update CarMapper.java with following code −

CarMapper.java

package com.tutorialspoint.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;

@Mapper
public interface CarMapper {
   @Mapping(source = "name", target = "name", defaultValue = "Sample")
   @Mapping(target = "brand", constant = "BMW")
   @Mapping(source = "price", target = "price", numberFormat = "$#.00")
   @Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy")
   Car getModelFromEntity(CarEntity carEntity);
}

使用以下代码更新 CarMapperTest.java −

Update CarMapperTest.java with following code −

CarMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.GregorianCalendar;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;

public class CarMapperTest {
   private CarMapper carMapper
      = Mappers.getMapper(CarMapper.class);

   @Test
   public void testEntityToModel() {
      CarEntity entity = new CarEntity();
      entity.setPrice(345000);
      entity.setId(1);
      entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));
      Car model = carMapper.getModelFromEntity(entity);
      assertEquals(model.getPrice(), "$345000.00");
      assertEquals(entity.getId(), model.getId());
      assertEquals("05.04.2015", model.getManufacturingDate());
      assertEquals("Sample", model.getName());
      assertEquals("BMW", model.getBrand());
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Using defaultExpression

使用 Mapstruct,我们可以使用 @Mapping 注解的 defaultExpression 属性在源属性为 null 的情况下使用 defaultExpression 传递计算值。

Using Mapstruct we can pass a computed value using defaultExpression in case source property is null using defaultExpression attribute of @Mapping annotation.

Syntax

@Mapping(target = "target-property", source="source-property" defaultExpression = "default-value-method")

此处:

Here

  1. default-value-method − target-property will be set as result of default-value-method in case source-property is null.

以下示例演示了相同内容。

Following example demonstrates the same.

Example

在 Eclipse 中打开映射,在 Mapping Using defaultValue 章节中更新。

Open project mapping as updated in Mapping Using defaultValue chapter in Eclipse.

使用以下代码更新 CarEntity.java −

Update CarEntity.java with following code −

CarEntity.java

package com.tutorialspoint.entity;
import java.util.GregorianCalendar;

public class CarEntity {
   private int id;
   private double price;
   private GregorianCalendar manufacturingDate;
   private String name;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public double getPrice() {
      return price;
   }
   public void setPrice(double price) {
      this.price = price;
   }
   public GregorianCalendar getManufacturingDate() {
      return manufacturingDate;
   }
   public void setManufacturingDate(GregorianCalendar manufacturingDate) {
      this.manufacturingDate = manufacturingDate;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

使用以下代码更新 Car.java −

Update Car.java with following code −

Car.java

package com.tutorialspoint.model;
public class Car {
   private int id;
   private String price;
   private String manufacturingDate;
   private String brand;
   private String name;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getPrice() {
      return price;
   }
   public void setPrice(String price) {
      this.price = price;
   }
   public String getManufacturingDate() {
      return manufacturingDate;
   }
   public void setManufacturingDate(String manufacturingDate) {
      this.manufacturingDate = manufacturingDate;
   }
   public String getBrand() {
      return brand;
   }
   public void setBrand(String brand) {
      this.brand = brand;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

使用以下代码更新 CarMapper.java −

Update CarMapper.java with following code −

CarMapper.java

package com.tutorialspoint.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;
import java.util.UUID;

@Mapper( imports = UUID.class )
public interface CarMapper {
   @Mapping(source = "name", target = "name", defaultExpression = "java(UUID.randomUUID().toString())")
   @Mapping(target = "brand", constant = "BMW")
   @Mapping(source = "price", target = "price", numberFormat = "$#.00")
   @Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy")
   Car getModelFromEntity(CarEntity carEntity);
}

使用以下代码更新 CarMapperTest.java −

Update CarMapperTest.java with following code −

CarMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.GregorianCalendar;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;

public class CarMapperTest {
   private CarMapper carMapper=Mappers.getMapper(CarMapper.class);

   @Test
   public void testEntityToModel() {
      CarEntity entity = new CarEntity();
      entity.setPrice(345000);
      entity.setId(1);
      entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));
      Car model = carMapper.getModelFromEntity(entity);
      assertEquals(model.getPrice(), "$345000.00");
      assertEquals(entity.getId(), model.getId());
      assertEquals("05.04.2015", model.getManufacturingDate());
      assertNotNull(model.getName());
      assertEquals("BMW", model.getBrand());
   }
}

运行以下命令以测试映射。

Run the following command to test the mappings.

mvn clean test

Output

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Mapping List

使用 Mapstruct,我们可以以与映射基本类型类似的方式映射列表。要获取对象列表,我们应该提供一个可以映射对象的映射器方法。

Using Mapstruct we can map list in similar fashion as we map primitives. To get a list of objects, we should provide a mapper method which can map an object.

Syntax

@Mapper
public interface CarMapper {
   List<String> getListOfStrings(List<Integer> listOfIntegers);
   List<Car> getCars(List<CarEntity> carEntities);
   Car getModelFromEntity(CarEntity carEntity);
}

以下示例演示了相同内容。

Following example demonstrates the same.

Example

在 Eclipse 中打开映射,在 Mapping Using defaultExpression 章节中更新。

Open project mapping as updated in Mapping Using defaultExpression chapter in Eclipse.

使用以下代码更新 CarEntity.java −

Update CarEntity.java with following code −

CarEntity.java

package com.tutorialspoint.entity;
import java.util.GregorianCalendar;

public class CarEntity {
   private int id;
   private double price;
   private GregorianCalendar manufacturingDate;
   private String name;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public double getPrice() {
      return price;
   }
   public void setPrice(double price) {
      this.price = price;
   }
   public GregorianCalendar getManufacturingDate() {
      return manufacturingDate;
   }
   public void setManufacturingDate(GregorianCalendar manufacturingDate) {
      this.manufacturingDate = manufacturingDate;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

使用以下代码更新 Car.java −

Update Car.java with following code −

Car.java

package com.tutorialspoint.model;

public class Car {
   private int id;
   private String price;
   private String manufacturingDate;
   private String brand;
   private String name;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getPrice() {
      return price;
   }
   public void setPrice(String price) {
      this.price = price;
   }
   public String getManufacturingDate() {
      return manufacturingDate;
   }
   public void setManufacturingDate(String manufacturingDate) {
      this.manufacturingDate = manufacturingDate;
   }
   public String getBrand() {
      return brand;
   }
   public void setBrand(String brand) {
      this.brand = brand;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

使用以下代码更新 CarMapper.java −

Update CarMapper.java with following code −

CarMapper.java

package com.tutorialspoint.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;

import java.util.List;
import java.util.UUID;

@Mapper( imports = UUID.class )
public interface CarMapper {
   @Mapping(source = "name", target = "name", defaultExpression = "java(UUID.randomUUID().toString())")
   @Mapping(target = "brand", constant = "BMW")
   @Mapping(source = "price", target = "price", numberFormat = "$#.00")
   @Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy")
   Car getModelFromEntity(CarEntity carEntity);

   List<String> getListOfStrings(List<Integer> listOfIntegers);
   List<Car> getCars(List<CarEntity> carEntities);
}

使用以下代码更新 CarMapperTest.java −

Update CarMapperTest.java with following code −

CarMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;

public class CarMapperTest {
   private CarMapper carMapper
      = Mappers.getMapper(CarMapper.class);

   @Test
   public void testEntityToModel() {
      CarEntity entity = new CarEntity();
      entity.setPrice(345000);
      entity.setId(1);
      entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));

      CarEntity entity1 = new CarEntity();
      entity1.setPrice(445000);
      entity1.setId(2);
      entity1.setManufacturingDate(new GregorianCalendar(2015, 3, 5));

      List<CarEntity> carEntities = Arrays.asList(entity, entity1);

      Car model = carMapper.getModelFromEntity(entity);
      assertEquals("$345000.00",model.getPrice());
      assertEquals(entity.getId(), model.getId());

      assertEquals("BMW", model.getBrand());
      assertEquals("05.04.2015", model.getManufacturingDate());

      List<Integer> list = Arrays.asList(1,2,3);
      List<String> listOfStrings = carMapper.getListOfStrings(list);
      List<Car> listOfCars = carMapper.getCars(carEntities);

      assertEquals(3, listOfStrings.size());
      assertEquals(2, listOfCars.size());
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Mapping Map

使用 Mapstruct,我们可以使用 @MapMapping 注释创建映射对象映射。其他映射规则与我们迄今为止看到的一样。

Using Mapstruct we can create mapping of map objects using @MapMapping annotation. Other rules of mapping are same as we’ve seen so far.

Syntax

@Mapper
public interface UtilityMapper {
   @MapMapping(valueDateFormat = "dd.MM.yyyy")
   Map<String, String> getMap(Map<Long, GregorianCalendar> source);
}

以下示例演示了相同内容。

Following example demonstrates the same.

Example

在Eclipse中打开在 Mapping List 章节中更新的项目映射。

Open project mapping as updated in Mapping List chapter in Eclipse.

使用以下代码创建 UtilityMapper.java −

Create UtilityMapper.java with following code −

UtilityMapper.java

package com.tutorialspoint.mapper;

import java.util.GregorianCalendar;
import java.util.Map;

import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;

@Mapper
public interface UtilityMapper {
   @MapMapping(valueDateFormat = "dd.MM.yyyy")
   Map<String, String> getMap(Map<Long, GregorianCalendar> source);
}

使用以下代码创建 UtilityMapperTest.java −

Create UtilityMapperTest.java with following code −

UtilityMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.mapper.UtilityMapper;

public class UtilityMapperTest {
   private UtilityMapper utilityMapper
      = Mappers.getMapper(UtilityMapper.class);

   @Test
   public void testMapMapping() {
      Map<Long, GregorianCalendar> source = new HashMap<>();
      source.put(1L, new GregorianCalendar(2015, 3, 5));

      Map<String, String> target = utilityMapper.getMap(source);
      assertEquals("05.04.2015", target.get("1"));
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.327 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.UtilityMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Mapping Stream

使用 Mapstruct,我们可以像针对集合一样针对流创建映射。

Using Mapstruct we can create mapping of streams in the same way as we did for collections.

Syntax

@Mapper
public interface UtilityMapper {
   Stream<String> getStream(Stream<Integer> source);
}

以下示例演示了相同内容。

Following example demonstrates the same.

Example

在 Eclipse 中打开映射,在 Mapping Map 章节中更新。

Open project mapping as updated in Mapping Map chapter in Eclipse.

使用以下代码更新 UtilityMapper.java −

Update UtilityMapper.java with following code −

UtilityMapper.java

package com.tutorialspoint.mapper;

import java.util.GregorianCalendar;
import java.util.Map;
import java.util.stream.Stream;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;

@Mapper
public interface UtilityMapper {
   @MapMapping(valueDateFormat = "dd.MM.yyyy")
   Map<String, String> getMap(Map<Long, GregorianCalendar> source);
   Stream<String> getStream(Stream<Integer> source);
}

使用以下代码更新 UtilityMapperTest.java −

Update UtilityMapperTest.java with following code −

UtilityMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.mapper.UtilityMapper;

public class UtilityMapperTest {
   private UtilityMapper utilityMapper=Mappers.getMapper(UtilityMapper.class);

   @Test
   public void testMapMapping() {
      Map<Long, GregorianCalendar> source = new HashMap<>();
      source.put(1L, new GregorianCalendar(2015, 3, 5));

      Map<String, String> target = utilityMapper.getMap(source);
      assertEquals("05.04.2015", target.get("1"));
   }
   @Test
   public void testGetStream() {
      Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();

      Stream<String> strings = utilityMapper.getStream(numbers);
      assertEquals(4, strings.count());
   }
}

运行以下命令以测试映射。

Run the following command to test the mappings.

mvn clean test

Output

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.327 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.UtilityMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Mapping Enum

Mapstruct 自动映射枚举。同名的枚举会自动映射。如果是不同的名字,我们可以使用 @ValueMapping 注解来进行映射。

Mapstruct automatically maps enums. Enums with same name are mapped automatically. In case of different name, we can use @ValueMapping annotation to do the mapping.

Syntax

@Mapper
public interface UtilityMapper {
   @ValueMapping(source = "EXTRA", target = "SPECIAL")
   PlacedOrderType getEnum(OrderType order);
}

以下示例演示了相同内容。

Following example demonstrates the same.

Example

在 Eclipse 中打开在 Mapping Stream 章节中更新的项目映射。

Open project mapping as updated in Mapping Stream chapter in Eclipse.

使用以下代码创建 OrderType.java −

Create OrderType.java with following code −

OrderType.java

package com.tutorialspoint.enums;
public enum OrderType {
   EXTRA, NORMAL, STANDARD
}

使用以下代码创建 PlacedOrderType.java −

Create PlacedOrderType.java with following code −

PlacedOrderType.java

package com.tutorialspoint.enums;
public enum PlacedOrderType {
   SPECIAL, NORMAL, STANDARD
}

使用以下代码更新 UtilityMapper.java −

Update UtilityMapper.java with following code −

UtilityMapper.java

package com.tutorialspoint.mapper;

import java.util.GregorianCalendar;
import java.util.Map;
import java.util.stream.Stream;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.ValueMapping;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;

@Mapper
public interface UtilityMapper {
   @MapMapping(valueDateFormat = "dd.MM.yyyy")
   Map<String, String> getMap(Map<Long, GregorianCalendar> source);
   Stream<String> getStream(Stream<Integer> source);

   @ValueMapping(source = "EXTRA", target = "SPECIAL")
   PlacedOrderType getEnum(OrderType order);
}

使用以下代码更新 UtilityMapperTest.java −

Update UtilityMapperTest.java with following code −

UtilityMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;
import com.tutorialspoint.mapper.UtilityMapper;

public class UtilityMapperTest {
   private UtilityMapper utilityMapper=Mappers.getMapper(UtilityMapper.class);

   @Test
   public void testMapMapping() {
      Map<Long, GregorianCalendar> source = new HashMap<>();
      source.put(1L, new GregorianCalendar(2015, 3, 5));

      Map<String, String> target = utilityMapper.getMap(source);
      assertEquals("05.04.2015", target.get("1"));
   }
   @Test
   public void testGetStream() {
      Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();
      Stream<String> strings = utilityMapper.getStream(numbers);
      assertEquals(4, strings.count());
   }
   @Test
   public void testGetEnum() {
      PlacedOrderType placedOrderType = utilityMapper.getEnum(OrderType.EXTRA);
      PlacedOrderType placedOrderType1 = utilityMapper.getEnum(OrderType.NORMAL);
      PlacedOrderType placedOrderType2 = utilityMapper.getEnum(OrderType.STANDARD);
      assertEquals(PlacedOrderType.SPECIAL.name(), placedOrderType.name());
      assertEquals(PlacedOrderType.NORMAL.name(), placedOrderType1.name());
      assertEquals(PlacedOrderType.STANDARD.name(), placedOrderType2.name());
   }
}

运行以下命令以测试映射。

Run the following command to test the mappings.

mvn clean test

Output

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.256 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.UtilityMapperTest
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec

Results :

Tests run: 7, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Throwing Exception

Mapstruct 映射器允许抛出特定的异常。考虑自定义映射方法的情况下,我们需要在数据无效的情况下抛出自定义异常。

Mapstruct mapper allows throwing specific exception. Consider a case of custom mapping method where we want to throw our custom exception in case of invalid data.

Syntax

@Mapper(uses=DateMapper.class)
public interface UtilityMapper {
    CarEntity getCarEntity(Car car) throws ParseException;
}

以下示例演示了相同内容。

Following example demonstrates the same.

Example

在 Eclipse 中打开更新的 Mapping Enum 章节中的项目映射。

Open project mapping as updated in Mapping Enum chapter in Eclipse.

使用以下代码更新 UtilityMapper.java −

Update UtilityMapper.java with following code −

UtilityMapper.java

package com.tutorialspoint.mapper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.stream.Stream;

import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.ValueMapping;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;
import com.tutorialspoint.model.Car;

@Mapper(uses=DateMapper.class)
public interface UtilityMapper {
   @MapMapping(valueDateFormat = "dd.MM.yyyy")
   Map<String, String> getMap(Map<Long, GregorianCalendar> source);

   Stream<String> getStream(Stream<Integer> source);

   @ValueMapping(source = "EXTRA", target = "SPECIAL")
   PlacedOrderType getEnum(OrderType order);

   CarEntity getCarEntity(Car car) throws ParseException;
}

class DateMapper {
   public String asString(GregorianCalendar date) {
      return date != null ? new SimpleDateFormat( "yyyy-MM-dd" )
         .format( date.getTime() ) : null;
   }

   public GregorianCalendar asDate(String date) throws ParseException {
      Date date1 = date != null ? new SimpleDateFormat( "yyyy-MM-dd" )
         .parse( date ) : null;
      if(date1 != null) {
         return new GregorianCalendar(date1.getYear(), date1.getMonth(),date1.getDay());
      }
      return null;
   }
}

使用以下代码更新 UtilityMapperTest.java −

Update UtilityMapperTest.java with following code −

UtilityMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.text.ParseException;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;
import com.tutorialspoint.mapper.UtilityMapper;
import com.tutorialspoint.model.Car;

public class UtilityMapperTest {
   private UtilityMapper utilityMapper
      = Mappers.getMapper(UtilityMapper.class);

   @Test
   public void testMapMapping() {
      Map<Long, GregorianCalendar> source = new HashMap<>();
      source.put(1L, new GregorianCalendar(2015, 3, 5));

      Map<String, String> target = utilityMapper.getMap(source);
      assertEquals("2015-04-05", target.get("1"));
   }

   @Test
   public void testGetStream() {
      Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();

      Stream<String> strings = utilityMapper.getStream(numbers);
      assertEquals(4, strings.count());
   }

   @Test
   public void testGetEnum() {
      PlacedOrderType placedOrderType = utilityMapper.getEnum(OrderType.EXTRA);
      PlacedOrderType placedOrderType1 = utilityMapper.getEnum(OrderType.NORMAL);
      PlacedOrderType placedOrderType2 = utilityMapper.getEnum(OrderType.STANDARD);
      assertEquals(PlacedOrderType.SPECIAL.name(), placedOrderType.name());
      assertEquals(PlacedOrderType.NORMAL.name(), placedOrderType1.name());
      assertEquals(PlacedOrderType.STANDARD.name(), placedOrderType2.name());
   }

   @Test
   public void testGetCar() {
      Car car = new Car();
      car.setId(1);
      car.setManufacturingDate("11/10/2020");
      boolean exceptionOccured = false;
      try {
         CarEntity carEntity = utilityMapper.getCarEntity(car);
      } catch (ParseException e) {
         exceptionOccured = true;
      }
      assertTrue(exceptionOccured);
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.256 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.UtilityMapperTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec

Results :

Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
...

MapStruct - Using Custom Mapper

Mapstruct 映射器允许创建自定义映射器方法来映射对象。我们可以向映射器接口添加一个默认方法。

Mapstruct mapper allows creating a custom mapper method to map an object. To mapper interface, we can add a default method.

Syntax

@Mapper(uses=DateMapper.class)
public interface UtilityMapper {
   default Car getCar(CarEntity entity) {
      Car car = new Car();
      car.setId(entity.getId());
      car.setName(entity.getName());
      return car;
   }
}

以下示例演示了相同内容。

Following example demonstrates the same.

Example

在 Eclipse 中打开更新的 Mapping Enum 章节中的项目映射。

Open project mapping as updated in Mapping Enum chapter in Eclipse.

使用以下代码更新 UtilityMapper.java −

Update UtilityMapper.java with following code −

UtilityMapper.java

package com.tutorialspoint.mapper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.stream.Stream;

import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.ValueMapping;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;
import com.tutorialspoint.model.Car;

@Mapper(uses=DateMapper.class)
public interface UtilityMapper {
   @MapMapping(valueDateFormat = "dd.MM.yyyy")
   Map<String, String> getMap(Map<Long, GregorianCalendar> source);

   Stream<String> getStream(Stream<Integer> source);

   @ValueMapping(source = "EXTRA", target = "SPECIAL")
   PlacedOrderType getEnum(OrderType order);

   CarEntity getCarEntity(Car car) throws ParseException;

   default Car getCar(CarEntity entity) {
      Car car = new Car();
      car.setId(entity.getId());
      car.setName(entity.getName());
      return car;
   }
}

class DateMapper {
   public String asString(GregorianCalendar date) {
      return date != null ? new SimpleDateFormat( "yyyy-MM-dd" )
         .format( date.getTime() ) : null;
   }

   public GregorianCalendar asDate(String date) throws ParseException {
      Date date1 = date != null ? new SimpleDateFormat( "yyyy-MM-dd" )
         .parse( date ) : null;
      if(date1 != null) {
         return new GregorianCalendar(date1.getYear(), date1.getMonth(),date1.getDay());
      }
      return null;
   }
}

使用以下代码更新 UtilityMapperTest.java −

Update UtilityMapperTest.java with following code −

UtilityMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.text.ParseException;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;

import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;
import com.tutorialspoint.mapper.UtilityMapper;
import com.tutorialspoint.model.Car;

public class UtilityMapperTest {
   private UtilityMapper utilityMapper
      = Mappers.getMapper(UtilityMapper.class);

   @Test
   public void testMapMapping() {
      Map<Long, GregorianCalendar> source = new HashMap<>();
      source.put(1L, new GregorianCalendar(2015, 3, 5));

      Map<String, String> target = utilityMapper.getMap(source);
      assertEquals("2015-04-05", target.get("1"));
   }

   @Test
   public void testGetStream() {
      Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();
      Stream<String> strings = utilityMapper.getStream(numbers);
      assertEquals(4, strings.count());
   }

   @Test
   public void testGetEnum() {
      PlacedOrderType placedOrderType = utilityMapper.getEnum(OrderType.EXTRA);
      PlacedOrderType placedOrderType1 = utilityMapper.getEnum(OrderType.NORMAL);
      PlacedOrderType placedOrderType2 = utilityMapper.getEnum(OrderType.STANDARD);
      assertEquals(PlacedOrderType.SPECIAL.name(), placedOrderType.name());
      assertEquals(PlacedOrderType.NORMAL.name(), placedOrderType1.name());
      assertEquals(PlacedOrderType.STANDARD.name(), placedOrderType2.name());
   }

   @Test
   public void testGetCarEntity() {
      Car car = new Car();
      car.setId(1);
      car.setManufacturingDate("11/10/2020");
      boolean exceptionOccured = false;
      try {
         CarEntity carEntity = utilityMapper.getCarEntity(car);
      } catch (ParseException e) {
         exceptionOccured = true;
      }
      assertTrue(exceptionOccured);
   }

   @Test
   public void testGetCar() {
      CarEntity entity = new CarEntity();
      entity.setId(1);
      entity.setName("ZEN");

      Car car = utilityMapper.getCar(entity);

      assertEquals(entity.getId(), car.getId());
      assertEquals(entity.getName(), car.getName());
   }
}

运行以下命令测试映射。

Run the follwing command to test the mappings.

mvn clean test

命令成功后。验证输出。

Once command is successful. Verify the output.

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.256 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.UtilityMapperTest
Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec

Results :

Tests run: 9, Failures: 0, Errors: 0, Skipped: 0
...