
本文档旨在帮助开发者在使用 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 字段。
具体实现步骤如下:
-
定义 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; // DTO中使用Enum } public enum DocumentsEnum { MAIN, OTHER } -
创建 Mapper 接口:
创建 Mapper 接口,并定义两个方法:listMapper 用于映射 List,mapper 用于映射单个 Document 到 DocumentDTO。在 mapper 方法上使用 @Mapping 注解来忽略 Enum 字段。
import org.mapstruct.Mapper; import org.mapstruct.Mapping; import java.util.List; @Mapper public interface DocumentsMapper { ListlistMapper(List document); @Mapping(source = "type", target = "type", ignore = true) DocumentDTO mapper(Document document); } 解释:
- @Mapper 注解: 声明这是一个 MapStruct Mapper 接口。
- listMapper(List
document): 该方法负责将 List 映射到 List 。 MapStruct 会自动识别并调用 mapper(Document document) 方法来处理 List 中的每个元素。 - @Mapping(source = "type", target = "type", ignore = true):这个注解告诉 MapStruct 忽略从 Document 对象的 type 字段到 DocumentDTO 对象的 type 字段的映射。
-
使用 Mapper:
在你的代码中使用 Mapper 接口进行对象映射。
// 获取 DocumentsMapper 的实例 (MapStruct 会自动生成实现类) DocumentsMapper documentsMapper = Mappers.getMapper(DocumentsMapper.class); // 假设有一个 List
List documents = ...; // 使用 listMapper 进行映射 List documentDTOs = documentsMapper.listMapper(documents);
注意事项:
- 确保你的 MapStruct 依赖已正确配置。
- MapStruct 会自动生成 Mapper 接口的实现类,你无需手动编写。
- 如果需要自定义映射逻辑,可以使用 @AfterMapping 注解。
总结:
通过将 List 的映射和单个对象的映射分离,并在单个对象的 Mapper 方法上使用 @Mapping 注解,可以有效地忽略 Enum 类型的字段。这种方法确保了 MapStruct 能够正确处理 List 的映射,并按照你的配置忽略指定的字段。










