1. 环境配置

1.1 Apache Maven

Maven配置

  1. <properties>
  2. <org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
  3. </properties>
  4. ...
  5. <dependencies>
  6. <dependency>
  7. <groupId>org.mapstruct</groupId>
  8. <artifactId>mapstruct</artifactId>
  9. <version>${org.mapstruct.version}</version>
  10. </dependency>
  11. </dependencies>
  12. ...
  13. <build>
  14. <plugins>
  15. <plugin>
  16. <groupId>org.apache.maven.plugins</groupId>
  17. <artifactId>maven-compiler-plugin</artifactId>
  18. <version>3.8.1</version>
  19. <configuration>
  20. <source>1.8</source>
  21. <target>1.8</target>
  22. <annotationProcessorPaths>
  23. <path>
  24. <groupId>org.mapstruct</groupId>
  25. <artifactId>mapstruct-processor</artifactId>
  26. <version>${org.mapstruct.version}</version>
  27. </path>
  28. </annotationProcessorPaths>
  29. </configuration>
  30. </plugin>
  31. </plugins>
  32. </build>
  33. ...

2. 定义Mapper

2.1. 基本mappings

定义一个mapper, 只需要简单的定义一个java接口, 定义上映射方法, 给方法加上 org.mapstruct.Mapper 注解.

  • 例. 使用Java接口来定义一个mapper

    1. import org.mapstruct.Mapper
    2. @Mapper
    3. public interface CarMapper {
    4. @Mapping(source = "make", target = "manufacturer")
    5. @Mapping(source = "numberOfSeats", target = "seatCount")
    6. CarDto carToCarDto(Car car);
    7. @Mapping(source = "name", target = "fullName")
    8. PersonDto personToPersonDto(Person person);
    9. }

@Mapper注解会触发MapStruct代码生成器在build阶段, 生成一个 CarMapper 接口的实现.
CarCarDto 的映射:

  • 属性name相同, 会自动隐式映射.
  • 属性name不同, 可以通过 @Mapping 注解手动指定映射关系.
  • 通过@BeanMapping(ignoreByDefault = true) 来禁用自动默认映射, 要求必须要用 @Mapping 这种方式显式指定映射关系.

看一下自动生成的代码 carToCarDto()

  • 例: MapStruct生成的代码
    1. // GENERATED CODE
    2. public class CarMapperImpl implements CarMapper {
    3. @Override
    4. public CarDto carToCarDto(Car car) {
    5. if ( car == null ) {
    6. return null;
    7. }
    8. CarDto carDto = new CarDto();
    9. if ( car.getFeatures() != null ) {
    10. carDto.setFeatures( new ArrayList<String>( car.getFeatures() ) );
    11. }
    12. carDto.setManufacturer( car.getMake() );
    13. carDto.setSeatCount( car.getNumberOfSeats() );
    14. carDto.setDriver( personToPersonDto( car.getDriver() ) );
    15. carDto.setPrice( String.valueOf( car.getPrice() ) );
    16. if ( car.getCategory() != null ) {
    17. carDto.setCategory( car.getCategory().toString() );
    18. }
    19. carDto.setEngine( engineToEngineDto( car.getEngine() ) );
    20. return carDto;
    21. }
    22. @Override
    23. public PersonDto personToPersonDto(Person person) {
    24. //...
    25. }
    26. private EngineDto engineToEngineDto(Engine engine) {
    27. if ( engine == null ) {
    28. return null;
    29. }
    30. EngineDto engineDto = new EngineDto();
    31. engineDto.setHorsePower(engine.getHorsePower());
    32. engineDto.setFuel(engine.getFuel());
    33. return engineDto;
    34. }
    35. }