
本文档旨在解决在使用 MapStruct 进行对象映射时,如何正确忽略 Enum 类型字段的问题。我们将通过示例代码和详细解释,帮助你理解 MapStruct 的工作原理,并掌握忽略特定字段的正确姿势,避免不必要的映射错误,提高开发效率。
在使用 MapStruct 进行对象映射时,经常会遇到需要忽略某些字段的情况,特别是当涉及到 Enum 类型时。直接在列表的映射方法上使用 @Mapping(source = "type", target = "type", ignore = true) 可能会失效,因为该注解作用于列表本身,而非列表中的元素。
问题分析
问题的根源在于,MapStruct 在处理列表映射时,会遍历列表中的每个元素,并尝试将源对象中的字段映射到目标对象。如果直接在列表映射方法上使用 @Mapping 注解,它实际上作用于列表对象本身,而不是列表中的 Document 和 DocumentDTO 对象。因此,忽略 type 字段的设置无法生效。
解决方案
要解决这个问题,需要将映射过程分解为两个步骤:
将 @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<DocumentDTO> listMapper(List<Document> document);
    @Mapping(source = "type", target = "type", ignore = true)
    DocumentDTO mapper(Document document);
}使用方法
在需要进行映射的地方,注入 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<DocumentDTO> convertDocuments(List<Document> documents) {
        return documentsMapper.listMapper(documents);
    }
}注意事项
总结
通过将映射过程分解为列表映射和对象映射,并将 @Mapping 注解放在对象映射器上,可以有效地忽略 Enum 类型字段的映射。这种方法不仅适用于 Enum 类型,也适用于其他需要忽略的字段类型。理解 MapStruct 的工作原理,可以帮助你更灵活地使用它,提高开发效率。
以上就是使用 MapStruct 忽略 Enum 字段的正确方法的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号