依赖引入
Maven
<dependencies>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.2.Final</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.2.Final</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
Gradle
dependencies {
implementation 'org.mapstruct:mapstruct:1.4.2.Final'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
annotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'
testAnnotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'
}
compileJava {
options.compilerArgs += [
'-Amapstruct.suppressGeneratorTimestamp=true',
'-Amapstruct.suppressGeneratorVersionInfoComment=true',
'-Amapstruct.verbose=true'
]
}
使用方式
Entity定义:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private String sex;
private int age;
private String username;
private String password;
}
DTO定义:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDTO {
private String name;
private String sex;
private String age;
private String username;
private String address
}
定义转换接口:
@Mapper
public class UserConverter{
ViewConverter INSTANCE = Mappers.getMapper(UserConverter.class);
@Mappings({
@Mapping(source = "name", target = "name"),
@Mapping(source = "sex", target = "sex"),
@Mapping(target = "age", expression= "java(String.valueOf(age))"),
@Mapping(source = "username", target = "username"),
@Mapping(target = "username", ignore=true),
})
UserDTO domainToDto(User view);
}
测试:
public class test{
public static void main(String[] args){
User user = UserConverter.INSTANCE.domainToDto(dto);
}
}