本文介绍Java实体映射工具MapStruct,并演示常用实体映射。
一、项目搭建
新建一个Maven项目,引入依赖:
<properties>
<lombok.version>1.18.12</lombok.version>
<mapstruct.version>1.3.1.Final</mapstruct.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>8</source>
<target>8</target>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
二、工具类ConvertUtils:
public class ConvertUtils {
public static final String FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<>();
public static String integerToString(Integer age) {
return String.valueOf(age);
}
public static String longToString(Long times) {
SimpleDateFormat format = threadLocal.get();
if (null == format) {
format = new SimpleDateFormat(FORMAT);
threadLocal.set(format);
}
return format.format(times);
}
}
三、实体类、映射接口:
@Data
public class UserDto {
private String id;
private String name;
private Integer age;
private Long times;
public UserDto(String id, String name, Integer age,Long times) {
this.id = id;
this.name = name;
this.age = age;
this.times = times;
}
}
@Data
public class UserVo {
private String id;
private String name;
private String aliasName;
private String age;
private String times;
}
@Mapper(componentModel = "spring", uses = {ConvertUtils.class}, nullValueCheckStrategy = ALWAYS, nullValueMappingStrategy = RETURN_DEFAULT)
public interface UserMapper {
public static final UserMapper INSTANCE = Mappers.getMapper( UserMapper.class );
@Mapping(source = "name",target = "aliasName")
@Mapping(source = "age",target = "age",qualifiedByName = "integerToString")
@Mapping(source = "times",target = "times",qualifiedByName = "longToString")
UserVo dto2Vo(UserDto dto);
}
四、测试类及效果:
public class Test {
public static void main(String[] args) {
UserDto dto = new UserDto("1","test",66,1625042189037L);
UserVo userVo = UserMapper.INSTANCE.dto2Vo(dto);
System.out.println(userVo.toString());
}
}
测试验证OK。