https://blog.csdn.net/bigtree_3721/article/details/82787411
在使用SpringBoot中使用MongoTemplate时,数据库中数据会有_class字段.。_class的意义,在下面这个链接有很好的解答:
http://stackoverflow.com/questions/6810488/spring-data-mongodb-mappingmongoconverter-remove-class/
,其实就是说,为了在把document转换成Java对象时能够转换到具体的子类.。
要去掉的方法简单:DefaultMongoTypeMapper类的构造函数的第一个参数是Type在MongoDB中名字. 设置为null的话就不会在保存时自动添加_class属性.所以需要覆写
以下就是去除_class 字段的配置类,只需将代码复制即可直接使用。
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.convert.CustomConversions; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.convert.DbRefResolver; import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper; import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; /** * Create by JIUN·LIU at 2018/7/24 */ @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; } }
方式2:https://blog.csdn.net/a704397849/article/details/98094036
@Bean(name = "mongoTemplate") public MongoTemplate mongoTemplate(@Qualifier("mongoDbFactory") MongoDbFactory mongoDbFactory,MongoMappingContext context, BeanFactory beanFactory) { DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory); MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context); try { mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class)); } catch (NoSuchBeanDefinitionException ignore) { } //去掉_class字段 mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null)); return new MongoTemplate(mongoDbFactory,mappingConverter); }