当前位置: 首页 > 图灵资讯 > 技术篇> 使用 MapStruct 忽略 Enum 字段的正确姿势

使用 MapStruct 忽略 Enum 字段的正确姿势

来源:图灵教育
时间:2025-10-29 22:18:35

使用 mapstruct 忽略 enum 字段的正确姿势

本文旨在帮助开发者使用 MapStruct 如何正确忽略对象映射? Enum 类型字段。通过示例代码和详细解释,我们将显示如何配置 Mapper 为了实现对特定性的接口 Enum 忽略字段,避免不必要的映射错误。

在使用 MapStruct 对象映射有时需要忽略某些字段,特别是当涉及到对象映射时 Enum 类型。直接在 List 的 Mapper 方法上使用 @Mapping(source = "type", target = "type", ignore = true) 它可能不起作用。这是因为你实际上是在映射 List 对象,而不是 List 中包含的 Document 和 DocumentDTO 对象。

要解决这个问题,需要创建两个 Mapper 方法:一种用于处理 List 另一种用于处理的映射 Document 到 DocumentDTO 的映射。将 @Mapping 只有将注释添加到后者的方法中,才能正确忽略 Enum 字段。

具体实现步骤如下:

  1. 定义 Entity 和 DTO:

    首先,定义你的 Entity 类 Document 和 DTO 类 DocumentDTO。确保 DTO 中间的字段类型是 Enum。

    @Entity
    public class Document {
    
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private Integer id;
    
        private String type; ///Entity使用String
    }
    
    @Data
    public class DocumentDTO {
    
        private Integer id;
        private DocumentsEnum type; // Enum在DTO中使用
    }
    
    public enum DocumentsEnum {
        MAIN,
        OTHER
    }

  2. 创建 Mapper 接口:

    创建 Mapper 界面,并定义两种方法:listMapper 用于映射 List,mapper 用于单个映射 Document 到 DocumentDTO。在 mapper 方法上使用 @Mapping 注解来忽略 Enum 字段。

    快转字幕

    快转字幕

    新一代 AI 字幕工作站,为创作者提供字幕制作、学习资源、会议记录、字幕制作等场景,一键为您的视频生成准确的字幕。

    快转字幕357

    查看详情 快转字幕

    import org.mapstruct.Mapper;
    import org.mapstruct.Mapping;
    import java.util.List;
    
    @Mapper
    public interface DocumentsMapper {
    
        List<DocumentDTO> listMapper(List<Document> document);
    
        @Mapping(source = "type", target = "type", ignore = true)
        DocumentDTO mapper(Document document);
    }

    解释:

    • @Mapper 注解: 声明这是一个 MapStruct Mapper 接口。
    • listMapper(List<Document> document): 负责这种方法 List<Document> 映射到 List<DocumentDTO>。 MapStruct 会自动识别和调用 mapper(Document document) 方法来处理 List 中间的每一个元素。
    • @Mapping(source = "type", target = "type", ignore = true):这个解释告诉 MapStruct 忽略从 Document 对象的 type 字段到 DocumentDTO 对象的 type 字段映射。
  3. 使用 Mapper:

    在您的代码中使用 Mapper 对象映射接口。

    // 获取 DocumentsMapper 的实例 (MapStruct 实现类将自动生成)
    DocumentsMapper documentsMapper = Mappers.getMapper(DocumentsMapper.class);
    
    // 假设有一个 List<Document>
    List<Document> documents = ...;
    
    // 使用 listMapper 进行映射
    List<DocumentDTO> documentDTOs = documentsMapper.listMapper(documents);

注意事项:

  • 确保你的 MapStruct 依赖于正确的配置。
  • MapStruct 会自动生成 Mapper 您不需要手动编写接口实现类。
  • 如果需要自定义映射逻辑,可以使用 @AfterMapping 注解。

总结:

通过将 List 在单个对象中,映射与单个对象的映射分离 Mapper 方法上使用 @Mapping 注释可以有效地忽略 Enum 类型字段。这种方法保证了 MapStruct 能正确处理 List 并根据您的配置忽略指定的字段。

以上就是使用 MapStruct 忽略 Enum 更多关于图灵教育的其他相关文章,请关注字段正确姿势的详细内容!

相关标签:

java app ai enum 接口 对象

大家都在看:

如何理解Java中的观察者模式和事件机制? Java Queue接口常用的实现类是什么? 如何选择 如何在Java中实现面向对象的设计模式 如何使用Java实现员工出勤统计报表? 如何在Java中使用Formater格式化输出?