java - 如何正确使用 MapStruct @Mapping 和 @Mappings?
问题描述
嗨,我的问题是当我mvn clean package
构建 .jar 文件时,我遇到了一些看起来像这样的错误:
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /C:/Users/Cactus/Documents/GitHub/Microservice/b2b/b2b-warehouse/src/main/java/com/bit/microservices/b2b/warehouse/mapper/ICategoryBpsjMapper.java:[27,33] No property named "createdDate" exists in source parameter(s). Did you mean "reasonDeleted"?
[ERROR] /C:/Users/Cactus/Documents/GitHub/Microservice/b2b/b2b-warehouse/src/main/java/com/bit/microservices/b2b/warehouse/mapper/ICategoryBpsjMapper.java:[27,33] No property named "createdDate" exists in source parameter(s). Did you mean "reasonDeleted"?
[INFO] 2 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 16.438 s
[INFO] Finished at: 2020-11-30T10:55:21+07:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project b2b-warehouse: Compilation failure: Compilation failure:
[ERROR] /C:/Users/Cactus/Documents/GitHub/Microservice/b2b/b2b-warehouse/src/main/java/com/bit/microservices/b2b/warehouse/mapper/ICategoryBpsjMapper.java:[27,33] No property named "createdDate" exists in source parameter(s). Did you mean "reasonDeleted"?
[ERROR] /C:/Users/Cactus/Documents/GitHub/Microservice/b2b/b2b-warehouse/src/main/java/com/bit/microservices/b2b/warehouse/mapper/ICategoryBpsjMapper.java:[27,33] No property named "createdDate" exists in source parameter(s). Did you mean "reasonDeleted"?
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
但是当我通过引导仪表板运行我的项目并右键单击并启动我的项目时,它运行正常。我的 api 工作正常。我做一些尝试。
首先尝试我的代码如下所示,我的映射器文件如下所示:
@Mapper(componentModel = "spring")
public interface ICategoryBpsjMapper {
ICategoryBpsjMapper INSTANCE = Mappers.getMapper(ICategoryBpsjMapper.class);
@Mappings({
@Mapping(target = "createdDate", dateFormat = "dd-MM-yyyy HH:mm:ss"),
@Mapping(target = "modifiedDate",dateFormat = "dd-MM-yyyy HH:mm:ss")})
CategoryBpsjResponseDto entityToDto(CategoryBPSJ entity);
CategoryBPSJ DTOEntity(CategoryBPSJDto dto);
CategoryBPSJ updateEntityFromDto(CategoryBPSJDto dto, @MappingTarget CategoryBPSJ entity);
List<CategoryBpsjResponseDto> entityToDto(List<CategoryBPSJ> entityList);
List<CategoryBPSJ> DTOEnity(List<CategoryBPSJDto> dtoList);
}
这是我的实体:
@Data
@Entity
@Audited
@EntityListeners(AuditingEntityListener.class)
@EqualsAndHashCode(of = "id")
@ToString(of = {"id"})
@Table(name = "msCategoryBPSJ", uniqueConstraints = {
@UniqueConstraint(name = "uk_categoryBPSJName", columnNames = { "categoryBPSJName" })})
public class CategoryBPSJ extends AuditField implements Serializable {
private static final long serialVersionUID = 8062436315663828938L;
@Schema(description = "Id merupakan primary key dan harus disertakan ketika edit, tipe datanya Long", example = "0", required = true)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Schema(description = "kode kategori pengiriman", example = "BPSJCTH1", required = true)
@NotBlank(message = "Tidak Boleh Kosong")
private String categoryBPSCode;
@Schema(description = "nama kategori pengiriman", example = "Toko/Gudang Tujuan Tutup", required = true)
@NotBlank(message = "Tidak Boleh Kosong")
private String categoryBPSJName;
}
这是我扩展的 AuditField 类:
@MappedSuperclass
@Data
@Audited
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = { "createdDate", "modifiedDate", "isDeleted" }, allowGetters = true, allowSetters = false)
public class AuditField implements Serializable {
private static final long serialVersionUID = 6025082509703710749L;
@Schema(description = "Status di hapus", example = "false", required = false)
public Boolean isDeleted = false;
@Schema(description = "Alasan di hapus", example = "apa pun alasannya", required = false)
public String reasonDeleted = "";
@CreatedDate
private Date createdDate;
@LastModifiedDate
private Date modifiedDate;
@CreatedBy
private String createdBy;
@LastModifiedBy
private String modifiedBy;
}
这是我的 DTO AuditFieldDto 类:
@Data
public class CategoryBpsjResponseDto extends AuditFieldDto implements Serializable {
private static final long serialVersionUID = -422185482845439241L;
@Schema(description = "Id merupakan primary key dan harus disertakan ketika edit, tipe datanya Long", example = "0", required = true)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
@Schema(description = "kode kategori pengiriman", example = "BPSJCTH1", required = true)
@NotBlank(message = "Tidak Boleh Kosong")
public String categoryBPSCode;
@Schema(description = "nama kategori pengiriman", example = "Toko/Gudang Tujuan Tutup", required = true)
@NotBlank(message = "Tidak Boleh Kosong")
public String categoryBPSJName;
}
这是我的 AuditFieldDto 类:
@Data
public class AuditFieldDto implements Serializable {
private static final long serialVersionUID = 3758121148184815303L;
@Schema(description = "Status di hapus", example = "false", required = false)
public Boolean isDeleted = false;
@Schema(description = "Alasan di hapus", example = "apa pun alasannya", required = false)
public String reasonDeleted = "";
private String createdDate;
private String modifiedDate;
private String createdBy;
private String modifiedBy;
}
如您所见, AuditField 和 AuditFieldD 具有相同的字段,但是当我运行mvn clean package
它时,它会给我编译错误,就像我提到的问题的顶部一样。在错误消息中,似乎 mapstruct 无法正确找到该字段。然后我尝试删除@Mappings 和@Mapping 注释行,构建成功。看起来很可疑..因为当我使用 Boot Dashboard 运行时,这些注释可以正常工作。
这是我的 pom.xml :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bit.microservices</groupId>
<artifactId>b2b</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>b2b-warehouse</artifactId>
<groupId>com.bit.microservices.b2b</groupId>
<name>b2b-warehouse</name>
<description>B2B Warehouse Service</description>
<version>0.0.1-SNAPSHOT</version>
<url>http://projects.spring.io/spring-boot/</url>
<organization>
<name>Pivotal Software, Inc.</name>
<url>http://www.spring.io</url>
</organization>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
<lombok.version>1.18.16</lombok.version>
<org.mapstruct.version>1.4.1.Final</org.mapstruct.version>
</properties>
<dependencies>
<dependency>
<groupId>com.bit.microservices</groupId>
<artifactId>model</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-envers</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.bit.b2b</groupId>
<artifactId>security</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-ui -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.4.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.github.classgraph/classgraph -->
<dependency>
<groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId>
<version>4.8.90</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.8</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>13</source> <!-- depending on your project -->
<target>13</target> <!-- depending on your project -->
<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>${lombok.version}</version>
</path>
<path>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.3.4.RELEASE</version>
</path>
<!-- other annotation processors -->
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
如果我想在将项目构建为 .jar 文件时使用 @Mappings 和 @Mapping,我在项目中错过了什么mvn clean package
?
解决方案
我在这里找到了罪魁祸首,但我不知道为什么以及这是正确的做法,因为当我执行此代码时,它起作用了。好的,让我们开始吧,你可以在我的问题上检查我的 mapstruct 版本,这是我解决这个问题的方法:
首先,在我的 AuditField 和 AuditFieldDto 中,如您所见,我有 2 个以“ public
”数据类型编写的字段,起初我将所有字段都公开写入,但后来我的朋友来推荐我将其设为私有,但是我不小心我没有将其全部设为私有,这两个字段名为public Boolean isDeleted;
并且public String reasonDeleted;
是公共的,这就是错误通过它们的原因,它们工作正常并且错误转到我私下编写的另一行。
我只是随机悲惨地将他们的数据类型改回公共,你可以看到有 4 个字段写在私有字段中,它们是
@CreatedDate
private Date createdDate;
@LastModifiedDate
private Date modifiedDate;
@CreatedBy
private String createdBy;
@LastModifiedBy
private String modifiedBy;
所以我在我的 AuditFieldDto 和 AuditField 类中将它们全部更改为 public,我的 AuditField 类的完整代码如下所示:
@MappedSuperclass
@Data
@Audited
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = { "createdDate", "modifiedDate", "isDeleted" }, allowGetters = true, allowSetters = false)
public class AuditField implements Serializable {
private static final long serialVersionUID = 6025082509703710749L;
@Schema(description = "Status di hapus", example = "false", required = false)
public Boolean isDeleted;
@Schema(description = "Alasan di hapus", example = "apa pun alasannya", required = false)
public String reasonDeleted;
@CreatedDate
public Date createdDate;
@LastModifiedDate
public Date modifiedDate;
@CreatedBy
public String createdBy;
@LastModifiedBy
public String modifiedBy;
}
它适用于我的 AuditFieldDto 类,如下所示:
@Data
public class AuditFieldDto implements Serializable {
private static final long serialVersionUID = 3758121148184815303L;
@Schema(description = "Status di hapus", example = "false", required = false)
public Boolean isDeleted = false;
@Schema(description = "Alasan di hapus", example = "apa pun alasannya", required = false)
public String reasonDeleted = "";
public String createdDate;
public String modifiedDate;
public String createdBy;
public String modifiedBy;
}
当我运行mvn clean package
构建成功时!我运行了 .jar 文件,它工作了!我猜为什么???因为这个,我坚持了好几天。然后我尝试查看生成的文件,您可以在您的项目中找到生成的文件,target/generated-sources/annotations
并在映射器类文件中进行微调。这是我的,我只举一个生成代码的例子,因为另一个似乎没有任何问题。
这是里面的内容GENERATED FILE
(我们不应该编辑这个文件,只是为了查看):
@Component
public class ICategoryBpsjMapperImpl implements ICategoryBpsjMapper {
@Override
public CategoryBpsjResponseDto entityToDto(CategoryBPSJ entity) {
if ( entity == null ) {
return null;
}
CategoryBpsjResponseDto categoryBpsjResponseDto = new CategoryBpsjResponseDto();
if ( entity.createdDate != null ) {
categoryBpsjResponseDto.createdDate = new SimpleDateFormat( "dd-MM-yyyy HH:mm:ss" ).format( entity.createdDate );
}
if ( entity.modifiedDate != null ) {
categoryBpsjResponseDto.modifiedDate = new SimpleDateFormat( "dd-MM-yyyy HH:mm:ss" ).format( entity.modifiedDate );
}
categoryBpsjResponseDto.isDeleted = entity.isDeleted;
categoryBpsjResponseDto.reasonDeleted = entity.reasonDeleted;
categoryBpsjResponseDto.createdBy = entity.createdBy;
categoryBpsjResponseDto.modifiedBy = entity.modifiedBy;
return categoryBpsjResponseDto;
}
}
您会看到他们在没有 get 和 set 的情况下访问该属性(我的意思是 getter setter),我认为这是导致我的错误的罪魁祸首,因为当我将该字段标记为私有时,如果代码是这样编写的,他们将无法被访问。现在这是我解决它的方式。
如果有人有更好的答案,我会将他们的答案作为已接受的答案,如果我的代码不正确或不合适,请等待。