Mongo之SpringBoot集成——配置MongoDB去掉

it2023-02-09  46

一、情景

SpringBoot项目中,引入Mongo,项目启动时,会自动创建配置的相关Collection信息。如果代码中有Document保存信息,则会自动创建Document及相关字段,默认创建的字段包括字段:_class。根据业务需求,则不需要保存该字段。

二、代码实现

设置Mongo配置信息

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 */ @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; } }

 

最新回复(0)