MapStruct

1. 使用

  1. 依赖

    <properties>
      <org.projectlombok.version>1.18.10</org.projectlombok.version>
      <org.mapstruct.version>1.3.0.Final</org.mapstruct.version>
    </properties>
    
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${org.projectlombok.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mapstruct</groupId>
      <artifactId>mapstruct</artifactId>
      <version>${org.mapstruct.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mapstruct</groupId>
      <artifactId>mapstruct-jdk8</artifactId>
      <version>${org.mapstruct.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mapstruct</groupId>
      <artifactId>mapstruct-processor</artifactId>
      <version>${org.mapstruct.version}</version>
    </dependency>
    
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.8.1</version>
      <configuration>
        <source>11</source>
        <target>11</target>
        <encoding>UTF-8</encoding>
        <annotationProcessorPaths>
          <path>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-processor</artifactId>
            <version>${org.mapstruct.version}</version>
          </path>
          <path>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${org.projectlombok.version}</version>
          </path>
        </annotationProcessorPaths>
      </configuration>
    </plugin>
    
  2. 使用

    1. 自建实体类、VO、DTO等对象。

    2. 定义映射接口

      @Mapper(componentModel = "spring")
      public interface ArticleMapper {
        @Mappings({
          @Mapping(source = "article.id", target = "id")
        })
        ArticleVo entityToVo(Article article, List<ArticleSortsVo> articleSortsVo, List<ArticleTagsVo> articleTagsVo);
      }
      
    3. 直接运行,会自动生成对应的实现类。

2. 坑

  1. No property named "updatedDate" exists in source parameter(s). Did you mean "empty"?
    

    原因:可能Lombok与MapStruct版本不一致,或者是因为Lombok在Mapstruct之后编译导致的问题。经过测试

    <org.projectlombok.version>1.18.10</org.projectlombok.version>
    <org.mapstruct.version>1.3.0.Final</org.mapstruct.version>
    

    是比较好的组合。

  2. 别忘了添加plugins中的配置。

Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2022-11-26 20:03:31

results matching ""

    No results matching ""