You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot操作MongoDB写入时如何禁用自动生成的_class字段?

不需要自定义序列化器,Spring Data MongoDB已经提供了原生配置可以直接关闭_class字段的自动写入,以下是两种常用实现方案:

方案1:配置文件直接配置(适用于Spring Boot 2.4及以上版本)

直接在application.yml中添加如下配置即可一键关闭:

spring:
  data:
    mongodb:
      mapping:
        type-key: ''

如果用application.properties格式,配置为:

spring.data.mongodb.mapping.type-key=

方案2:自定义Mongo配置类(全版本通用)

如果用的是旧版本Spring Boot,不支持上述配置,可以通过注册配置类实现:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;

@Configuration
public class MongoConfig {
    @Bean
    public MongoTemplate mongoTemplate(MappingMongoConverter mappingMongoConverter) {
        // 传入null表示禁用类型字段的写入,也就是移除默认的_class字段
        mappingMongoConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return new MongoTemplate(mappingMongoConverter.getMongoDatabaseFactory(), mappingMongoConverter);
    }
}

注意事项

  • 如果你项目中使用了多态实体映射(同一个集合存储多个不同子类的实体数据),关闭_class后Spring Data MongoDB无法自动识别反序列化的目标类型,会报错,这种场景需要额外手动配置类型映射。如果你的项目是单实体类对应单集合,不会有任何影响。
  • _id是MongoDB内置的必填字段,即使实体类没有显式声明,MongoDB也会自动生成,符合你保留_id的需求。

内容的提问来源于stack exchange,提问作者djangofan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 00:57:02