Spring Data MongoDB Remove _class Column
By default, SpringData’s MappingMongoConverter
add an extra “_class” column for every object saved in MongoDB. For example,
public class User { String username; String password; //...getters and setters }
Save it
MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate"); User user = new User("mkyong", "password123"); mongoOperation.save(user, "users");
Result
> db.users.find() { "_class" : "com.mkyong.user.User", "_id" : ObjectId("5050aef830041f24ff2bd16e"), "password" : "new password", "username" : "mkyong" }
SpringData created this extra “_class” for a reason. To remove this extra “_class“, override the MappingMongoConverter
, and passing a new DefaultMongoTypeMapper(null)
.
Here we show you how to remove the _class in annotation or XML way.
1. Annotation
@Configuration public class SpringMongoConfig{ public @Bean MongoDbFactory mongoDbFactory() throws Exception { return new SimpleMongoDbFactory(new Mongo(), "database"); } public @Bean MongoTemplate mongoTemplate() throws Exception { //remove _class MappingMongoConverter converter = new MappingMongoConverter(mongoDbFactory(), new MongoMappingContext()); converter.setTypeMapper(new DefaultMongoTypeMapper(null)); MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory(), converter); return mongoTemplate; } }
2. XML
Same thing, but in XML file.
<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>
3. Test it Again
Save it again, the “_class” is gone.
> db.users.find() { "_id" : ObjectId("random code"), "password" : "new password", "username" : "mkyong" }
References
- StackOverflow – MappingMongoConverter remove _class
- Spring Forum – MappingMongoConverter remove _class
출처 - http://www.mkyong.com/mongodb/spring-data-mongodb-remove-_class-column/
'Framework & Platform > Spring' 카테고리의 다른 글
spring - @MVC에서 favicon.ico 처리 (0) | 2013.06.10 |
---|---|
spring data - mongodb 도메인 객체에서 사용되는 annotation (0) | 2013.06.06 |
spring data - mongoTemplate CRUD example (0) | 2013.05.29 |
spring data - mongodb 설정 예제 (0) | 2013.05.19 |
spring - ehcache config (0) | 2013.04.16 |