
本文档旨在解决在使用 MapStruct 进行对象映射时,如何正确忽略 Enum 类型字段的问题。我们将通过示例代码和详细解释,帮助你理解 MapStruct 的工作原理,并掌握忽略特定字段的正确姿势,避免不必要的映射错误,提高开发效率。
在使用 MapStruct 进行对象映射时,经常会遇到需要忽略某些字段的情况,特别是当涉及到 Enum 类型时。直接在列表的映射方法上使用 @Mapping(source = "type", target = "type", ignore = true) 可能会失效,因为该注解作用于列表本身,而非列表中的元素。
问题分析
问题的根源在于,MapStruct 在处理列表映射时,会遍历列表中的每个元素,并尝试将源对象中的字段映射到目标对象。如果直接在列表映射方法上使用 @Mapping 注解,它实际上作用于列表对象本身,而不是列表中的 Document 和 DocumentDTO 对象。因此,忽略 type 字段的设置无法生效。
解决方案
要解决这个问题,需要将映射过程分解为两个步骤:
- 列表映射器: 负责处理列表的映射。
- 对象映射器: 负责处理 Document 到 DocumentDTO 的单个对象映射。
将 @Mapping 注解放在对象映射器上,才能正确地忽略 type 字段。
示例代码
假设有以下实体类 Document 和 DTO 类 DocumentDTO:
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@Data
public class Document {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
private String type;
}import lombok.Data;
@Data
public class DocumentDTO {
private Integer id;
private DocumentsEnum type;
}其中 DocumentsEnum 是一个枚举类型,定义如下:
public enum DocumentsEnum {
MAIN,
SECONDARY
}现在,创建 DocumentsMapper 接口,并定义两个映射方法:
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import java.util.List;
@Mapper
public interface DocumentsMapper {
List listMapper(List document);
@Mapping(source = "type", target = "type", ignore = true)
DocumentDTO mapper(Document document);
} - listMapper 方法负责将 List
映射到 List 。 - mapper 方法负责将单个 Document 对象映射到 DocumentDTO 对象。
- @Mapping(source = "type", target = "type", ignore = true) 注解位于 mapper 方法上,指示 MapStruct 忽略 Document 对象的 type 字段到 DocumentDTO 对象的 type 字段的映射。
使用方法
在需要进行映射的地方,注入 DocumentsMapper 接口,并调用 listMapper 方法即可:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DocumentService {
@Autowired
private DocumentsMapper documentsMapper;
public List convertDocuments(List documents) {
return documentsMapper.listMapper(documents);
}
} 注意事项
- 确保 MapStruct 依赖已正确添加到项目中。
- @Mapper 注解用于告诉 MapStruct 这是一个映射器接口。
- @Mapping 注解用于指定字段映射规则,ignore = true 表示忽略该字段的映射。
- 将映射过程分解为列表映射和对象映射,可以更灵活地控制映射行为。
总结
通过将映射过程分解为列表映射和对象映射,并将 @Mapping 注解放在对象映射器上,可以有效地忽略 Enum 类型字段的映射。这种方法不仅适用于 Enum 类型,也适用于其他需要忽略的字段类型。理解 MapStruct 的工作原理,可以帮助你更灵活地使用它,提高开发效率。










