spring mongodb中去掉_class列
Posted yweihainan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring mongodb中去掉_class列相关的知识,希望对你有一定的参考价值。
调用mongoTemplate的save方法时, spring-data-mongodb的TypeConverter会自动给document添加一个_class属性, 值是你保存的类名. 这种设计并没有什么坏处. spring-data-mongodb是为了在把document转换成Java对象时能够转换到具体的子类. 但有时候我们并不希望出现这个字段, 主要是看上去会比较"烦". 可以通过设置MappingMongoConverter的MongoTypeMapper来解决这个问题.
DefaultMongoTypeMapper类的构造函数的第一个参数是Type在MongoDB中名字. 设置为null的话就不会在保存时自动添加_class属性.所以需要覆写
spring的配置文件方式:
<mongo:mongo host="localhost" port="27017" /> <mongo:db-factory dbname="database" /> <bean id="mappingContext" class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" /> <bean id="defaultMongoTypeMapper" class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper"> <constructor-arg name="typeKey"><null/></constructor-arg> </bean> <bean id="mappingMongoConverter" class="org.springframework.data.mongodb.core.convert.MappingMongoConverter"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /> <constructor-arg name="mappingContext" ref="mappingContext" /> <property name="typeMapper" ref="defaultMongoTypeMapper" /> </bean> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /> <constructor-arg name="mongoConverter" ref="mappingMongoConverter" /> </bean>
注解方式:
@EnableMongoRepositories( basePackages = {"com.dhp"}, repositoryFactoryBeanClass = DHBMongoRepositoryFactoryBean.class ) @PropertySource("classpath:mongo.properties") @EnableMongoAuditing public class MongoConfig extends AbstractMongoConfiguration { @Value("${mongo.connectionString}") private String connectionString; @Value("${mongo.dbName}") private String dbName; @Autowired private ApplicationContext appContext; @Override protected String getDatabaseName() { return dbName; } @Override @Bean public Mongo mongo() throws Exception { MongoClientURI mongoClientURI = new MongoClientURI(connectionString); return new MongoClient(mongoClientURI); } @Override @Bean public MongoTemplate mongoTemplate() throws Exception { MongoDbFactory factory = mongoDbFactory(); MongoMappingContext mongoMappingContext = new MongoMappingContext(); mongoMappingContext.setApplicationContext(appContext); MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(factory), mongoMappingContext); converter.setTypeMapper(new DefaultMongoTypeMapper(null)); return new MongoTemplate(factory, converter); } @Bean public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { return new PropertySourcesPlaceholderConfigurer(); } }
当使用Servlet 3初始化确保添加应用程序上下文到mongo中,如果不加上这两句,会报异常:org.springframework.expression.spel.SpelEvaluationException
@Autowired
private ApplicationContext appContext;
mongoMappingContext.setApplicationContext(appContext);
以上是关于spring mongodb中去掉_class列的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Spring Boot 集成测试中使用嵌入式 MongoDB
[记录] springboot-mongo 去除_class 字段