SpringBoot配置MongoDB去掉_class字段

本文介绍如何在使用Spring Data MongoDB时移除默认添加到集合中的_class键,适用于那些不需要处理继承关系且模型较为简单的场景。通过覆盖默认的MappingMongoConverter实现这一目的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

When using spring data mongo it by default adds a _class key to your collection to be able to handle inheritance.
But if your domain model is simple and flat, you can remove it by overriding the default MappingMongoConverter

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.*;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

/**
 * @description:
 * When using spring data mongo it by default adds a _class key to your collection to be able to handle inheritance.
 * But if your domain model is simple and flat, you can remove it by overriding the default MappingMongoConverter
 * @author:@luomouren.
 * @Date:2017-12-03 21:26
 */
@Configuration
public class MongoConfig {

    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
        try {
            mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
        } catch (NoSuchBeanDefinitionException ignore) {
        }

        // Don't save _class to mongo
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));

        return mappingConverter;
    }

}
### 如何在 Spring Boot 中集成 MongoDB 并忽略 `_class` 字段 在使用 Spring Data MongoDB 进行开发时,默认情况下,Spring 会在文档中存储一个名为 `_class` 的字段。这个字段用于记录实体类的全限定名(FQCN),以便支持多态查询和其他功能[^1]。然而,在某些场景下,开发者可能希望禁用这一行为。 可以通过以下方法来实现忽略 `_class` 字段: #### 方法一:全局配置 通过自定义 `MongoCustomConversions` 或者设置 `MappingContext` 来控制映射行为。具体来说,可以创建一个 Bean 定义并覆盖默认的行为: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.MongoDatabaseFactory; import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; @Configuration public class MongoConfig { @Bean public MappingMongoConverter mappingMongoConverter(MongoDatabaseFactory mongoDatabaseFactory, MongoMappingContext mongoMappingContext) { MappingMongoConverter converter = new MappingMongoConverter( new DefaultDbRefResolver(mongoDatabaseFactory), mongoMappingContext); // 关键一步:关闭 _class 字段的保存 converter.setTypeMapper(new DefaultMongoTypeMapper(null)); return converter; } } ``` 上述代码的关键在于调用了 `setTypeMapper` 方法,并传入了一个新的 `DefaultMongoTypeMapper` 实例,其中参数为 `null`。这会告诉 Spring 不要在数据库中写入 `_class` 字段[^2]。 --- #### 方法二:局部配置 如果不想影响整个项目,而是针对特定的实体类忽略 `_class` 字段,则可以在该类上添加注解 `@Document` 和其他相关属性: ```java import org.springframework.data.annotation.TypeAlias; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "users") @TypeAlias("User") // 使用别名替代完整的 FQCN public class User { private String id; private String name; private int age; // Getters and Setters... } ``` 这里的 `@TypeAlias` 注解允许指定一个短名称作为类型标记,从而减少冗余信息的同时避免显式的 `_class` 存储[^3]。 --- #### 验证效果 完成以上任一种方式后,重新运行应用程序并通过 Postman 或其他工具测试 CRUD 功能。此时再查看 MongoDB 数据库中的实际存储结构,应该已经看不到 `_class` 字段的存在[^4]。 --- ### 注意事项 尽管移除 `_class` 能够简化数据模型,但在涉及继承关系或者复杂对象图的情况下可能会带来兼容性问题。因此建议仅当确实不需要此类元数据时才执行这些操作。 ---
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值