在spring for mongodb中,会
发现当一个pojo
序列化为一个document时,会出现如下
情况:
public class User {
String username;
String password;
}
转变为mongodb 时
MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
User user = new User("abc", "password123");
mongoOperation.save(user, "users");
会发现document中,多了个_class属性:
{
"_class" : "com.abc.user.User",
...................
}
多了_class的
意义,在下面这个链接有很好的解答:
http://stackoverflow.com/questions/6810488/spring-data-mongodb-mappingmongoconverter-remove-class/
,其实就是说,为了在把document转换成Java对象时能够转换到具体的子类.
要去掉的方法简单:
DefaultMongoTypeMapper类的
构造函数的第一个参数是Type在MongoDB中名字. 设置为null的话就不会在保存时自动添加_class属性.所以需要覆写
MappingMongoConverter。
1)用
注解的方法取消:
@Configuration
public class SpringMongoConfig{
public @Bean
MongoDbFactory mongoDbFactory() throws Exception {
return new SimpleMongoDbFactory(new Mongo(), "database");
}
public @Bean
MongoTemplate mongoTemplate() throws Exception {
MappingMongoConverter converter =
new MappingMongoConverter(mongoDbFactory(), new MongoMappingContext());
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory(), converter);
return mongoTemplate;
}
2)XML配置文件
<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>