MVC三层模型中,需要将Entity、DTO、VO对象来回做转换,常用的对象转换工具有BeanUtils、Dozer等,这里介绍个更好用的工具mapstruct。效率更高的原因是前者都是在运行时基于反射方式实现,而mapstruct在编译阶段已经生成对应的转换方法。
1、引入依赖jar包
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</dependency>
2、官方网站提供了一种插件的方式:
<properties>
<org.mapstruct.version>1.3.0.Final</org.mapstruct.version>
</properties>
...
<dependencies>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
</dependencies>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version> <!-- or newer version -->
<configuration>
<source>1.8</source> <!-- depending on your project -->
<target>1.8</target> <!-- depending on your project -->
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</path>
<!-- other annotation processors -->
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
我们选择第一种方式即可。以下是使用方式
@Mapper(componentModel = "spring")
public interface AppointmentOrderConverter {
@Mappings({
@Mapping(source = "request.arrivalTime", target = "arrivalTime", dateFormat = "yyyy-MM-dd HH:mm"),
@Mapping(source = "userId", target = "userId"),
@Mapping(target = "applicationTime", expression = "java(com.ftcs.core.utils.DateUtil.currentDate())"),
@Mapping(target = "createTime", expression = "java(com.ftcs.core.utils.DateUtil.currentDate())"),
@Mapping(target = "updateTime", expression = "java(com.ftcs.core.utils.DateUtil.currentDate())"),
@Mapping(target = "status", expression = "java(com.ftcs.core.common.context.AppointmentStatusEnum.TO_BE_PROCESSED.getCode())"),
@Mapping(target = "isDelete", constant = "0"),
@Mapping(target = "loanStatus", constant = "0")
})
AppointmentOrder request2domain(AppointmentRequest request, Long userId);
}
注解@Mapper和@Mapping
@Mapper 只有在接口加上这个注解, MapStruct 才会去实现该接口。@Mapper 里有个 componentModel 属性,主要是指定实现类的类型,一般用到两个属性
default:默认,可以通过 Mappers.getMapper(Class) 方式获取实例对象
spring:在接口的实现类上自动添加注解 @Component,可通过 @Autowired 方式注入
@Mapping:属性映射,若源对象属性与目标对象名字一致,会自动映射对应属性
source:源属性
target:目标属性
dateFormat:String 到 Date 日期之间相互转换,通过 SimpleDateFormat,该值为 SimpleDateFormat的日期格式
ignore: 忽略这个字段
@Mappings:配置多个@Mapping
@MappingTarget 用于更新已有对象
@InheritConfiguration 用于继承配置