Mapstruct - 在整个项目中按名称忽略字段

Mapstruct - ignore field by name in whole project

我有一个项目,我经常在其中映射 dto -> db 模型。几乎我所有的数据库模型都有一些额外的字段,比如版本,这些字段永远不会从 dto 映射。

是否有任何可能性或优雅的解决方法来全局忽略目标字段的名称?

现在我必须使用 @Mapping(target = "version", ignore = true)。不能使用 @Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE),因为我想在不小心遗漏任何重要的 属性 时得到警告或错误。我使用 '-Amapstruct.unmappedTargetPolicy=WARN' 控制默认行为,我在开发新功能期间将其更改为错误。

有些人可能会说这些只是警告,但是当它们很多时,就很难发现错误。

Mapstruct 1.3.1.Final,可能会在不久的将来移动到 1.4.1.Final。搜索了 docs,但找不到任何有用的东西。

提前感谢您的回答:)

Some people may say that these are just warnings, but when there are many of them, it makes it harder to spot mistakes.

首先,很高兴您没有忽视警告。

从 MapStruct 1.4 开始,您可以创建由多个映射组成的注释。在 MapStruct 1.4.1 的文档中阅读更多内容。 3.2. Mapping Composition (experimental). This configuration can also be shared (11.3. Shared configurations).

@Retention(RetentionPolicy.CLASS)
@Mapping(target = "version", ignore = true)
public @interface WithoutVersion { }
@Mapper
public interface DtoMapper {
   
   @WithoutVersion
   Dto entityToDto(Entity entity)
}

这在要忽略多个字段的情况下很有用。最大的优点是您可以通过显式使用注释而不是全局配置来控制映射。

@Retention(RetentionPolicy.CLASS)
@Mapping(target = "version", ignore = true)
@Mapping(target = "createdAt", ignore = true)
@Mapping(target = "modifiedAt", ignore = true)
@Mapping(target = "id", ignore = true)
public @interface WithoutMetadata { }
@Mapper
public interface DtoMapper {
   
   @WithoutMetadata 
   Dto entityToDto(Entity entity)
}