我有一个项目,我经常在其中映射 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,但找不到任何有用的东西。
提前感谢您的回答:)
有些人可能会说这些只是警告,但是当警告太多时,就更难发现错误。
首先,我很高兴您没有忽略警告。
从 MapStruct 1.4 开始,您可以创建由多个映射组成的注释。请参阅 MapStruct 1.4.1 的文档了解更多信息。 3.2。映射组合(实验)。此配置也可以是共享(11.3.共享配置)。
@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)
}