Mapstruct的具体介绍与使用

  |  

mapstruct 简介

mapstruct 是一种 实体类 映射框架,能够通过 Java 注解将一个实体类的属性安全地赋值给另一个实体类。有了 mapstruct,只需要定义一个映射器接口,声明需要映射的方法,在编译过程中,mapstruct 会自动生成该接口的实现类,实现将源对象映射到目标对象的效果。

mapstruct 与其他映射对比

实体类映射框架大致有两种:一种是运行期通过 java 反射机制动态映射;另一种是编译期动态生成 getter/setter,在运行期直接调用框架编译好的 class 类实现实体映射。
由于 mapstruct 映射是在编译期间实现的,因此相比运行期的映射框架有以下几个优点:

  1. 安全性高。因为是编译期就实现源对象到目标对象的映射, 如果编译器能够通过,运行期就不会报错。
  2. 速度快。速度快指的是运行期间直接调用实现类的方法,不会在运行期间使用反射进行转化。

依赖包

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.3.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.3.Final</version>
</dependency>

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import org.mapstruct.Mapper;
import org.mapstruct.Named;
import org.mapstruct.factory.Mappers;

@Mapper
public interface UserConvert {

UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);

@Named("convert")
UserVO convert(User user);
}

// 使用
UserConvert.INSTANCE.convert(user)

注意

  1. 修改或者增加字段 需要清理 target
  2. 编译打包 需要把 mapstruct 放在 lombok 下面

springboot 打包配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.2.1</version>
<configuration>
<finalName>${project.build.finalName}</finalName>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>21</source>
<target>21</target>
<encoding>UTF-8</encoding>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.3.Final</version>
</path>
<path>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>3.2.1</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
文章目录
  1. 1. mapstruct 简介
  2. 2. mapstruct 与其他映射对比
  3. 3. 依赖包
  4. 4. 使用
  5. 5. 注意