PRELOADER

当前文章 : 《MapStruct在开发中的应用》

12/28/2019 —— 

介绍

MapStruct是一种类型安全的bean映射类生成java注释处理器。
在业务项目的开发中,我们经常需要将Java对象进行转换,比如从外部HSF服务得到的对象转换为本域的业务对象domain object,将Domain Object转为数据持久层的data Object,将domain object 转给dto以便返回给外部调用方等。在转换时大部分属性都是相同的,只有少部分的不同,如果手工编写转换代码,会很繁琐。这时我们可以通过一些对象转换框架来更方便的做这件事情。

使用

  1. 添加依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
 <!--mapStruct依赖-->  

<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
<scope>provided</scope>
</dependency>
  1. 创建模拟的两个实体如下:
  • 实体1:模拟服务传过来的实体
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Data
public class Demo1 {

private Integer id;

private Long userId;

private String indentSource;

private String ruleIndentId;

private BigDecimal goodsPrice;

private Integer status;

}
  • 实体2:自身项目中的实体
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Data
public class Demo2 {

private Integer id;

private Long userId;

private String indentSource;

private String ruleId;

private BigDecimal goodsPrice;

private Integer status;

}
  1. 配置MapStruct:
    到目前为止我们的准备工作差不多完成了,下面我们开始配置使用MapStruct。
  • 创建Mapper:Mapper这个定义一般是被广泛应用到MyBatis半自动化ORM框架上,而这里的Mapper跟Mybatis没有关系。

  • 默认配置,我们不需要做过多的配置内容,获取Mapper的方式就是采用Mappers通过动态工厂内部反射机制完成Mapper实现类的获取。

1
2
3
4
5
6
7
8
9
10
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DemoMapper {
DemoMapper MAPPER = Mappers.getMapper(DemoMapper.class);

//实体转换
@Mappings( {
@Mapping( source = "ruleIndentId",target = "ruleId"),
} )
Demo2 toDemo2(Demo1 demo1);
}
  • @Mapping注解我们用到了两个属性,分别是source、target。
1
source代表的是映射接口方法内的参数名称,如果是基本类型的参数,参数名可以直接作为source的内容,如果是实体类型,则可以采用实体参数名.字段名的方式作为source的内容,配置如上面DemoMapper内容所示。
1
target代表的是映射到方法方法值内的字段名称,配置如上面DemoMapper所示。

image

  1. 测试用例:
1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void contextLoads() {
Demo1 demo1 = new Demo1();
demo1.setId(1);
demo1.setUserId(111L);
demo1.setGoodsPrice(new BigDecimal(10));
demo1.setIndentSource("10003");
demo1.setRuleIndentId("123");
demo1.setStatus(1);
Demo2 demo2 = DemoMapper.MAPPER.toDemo2(demo1);
System.out.println(demo2.toString());
}

输出结果:

1
demo2{userId ='111',indentSource = '10003',ruleId = '123',goodsPrice = '10',status = '1'}

MapStruct 生成的:
image