依赖引入

  • Maven

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.mapstruct</groupId>
    4. <artifactId>mapstruct</artifactId>
    5. <version>1.4.2.Final</version>
    6. </dependency>
    7. <dependency>
    8. <groupId>org.projectlombok</groupId>
    9. <artifactId>lombok</artifactId>
    10. <version>1.18.16</version>
    11. </dependency>
    12. </dependencies>
    13. <build>
    14. <plugins>
    15. <plugin>
    16. <groupId>org.apache.maven.plugins</groupId>
    17. <artifactId>maven-compiler-plugin</artifactId>
    18. <configuration>
    19. <source>1.8</source>
    20. <target>1.8</target>
    21. <encoding>UTF-8</encoding>
    22. <annotationProcessorPaths>
    23. <path>
    24. <groupId>org.projectlombok</groupId>
    25. <artifactId>lombok</artifactId>
    26. <version>1.18.16</version>
    27. </path>
    28. <path>
    29. <groupId>org.mapstruct</groupId>
    30. <artifactId>mapstruct-processor</artifactId>
    31. <version>1.4.2.Final</version>
    32. </path>
    33. </annotationProcessorPaths>
    34. </configuration>
    35. </plugin>
    36. </plugins>
    37. </build>
  • Gradle

    1. dependencies {
    2. implementation 'org.mapstruct:mapstruct:1.4.2.Final'
    3. compileOnly 'org.projectlombok:lombok'
    4. annotationProcessor 'org.projectlombok:lombok'
    5. annotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'
    6. testAnnotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'
    7. }
    8. compileJava {
    9. options.compilerArgs += [
    10. '-Amapstruct.suppressGeneratorTimestamp=true',
    11. '-Amapstruct.suppressGeneratorVersionInfoComment=true',
    12. '-Amapstruct.verbose=true'
    13. ]
    14. }

    使用方式

Entity定义:

  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. public class User {
  5. private String name;
  6. private String sex;
  7. private int age;
  8. private String username;
  9. private String password;
  10. }

DTO定义:

  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. public class UserDTO {
  5. private String name;
  6. private String sex;
  7. private String age;
  8. private String username;
  9. private String address
  10. }

定义转换接口:

  1. @Mapper
  2. public class UserConverter{
  3. ViewConverter INSTANCE = Mappers.getMapper(UserConverter.class);
  4. @Mappings({
  5. @Mapping(source = "name", target = "name"),
  6. @Mapping(source = "sex", target = "sex"),
  7. @Mapping(target = "age", expression= "java(String.valueOf(age))"),
  8. @Mapping(source = "username", target = "username"),
  9. @Mapping(target = "username", ignore=true),
  10. })
  11. UserDTO domainToDto(User view);
  12. }

测试:

  1. public class test{
  2. public static void main(String[] args){
  3. User user = UserConverter.INSTANCE.domainToDto(dto);
  4. }
  5. }