调用mongoTemplate的save方法时, spring-data-mongodb的TypeConverter会自动给document添加一个_class属性, 值是你保存的类名. 这种设计并没有什么坏处. spring-data-mongodb是为了在把document转换成Java对象时能够转换到具体的子类. 但有时候我们并不希望出现这个字段, 主要是看上去会比较"烦". 可以通过设置MappingMongoConverter的MongoTypeMapper来解决这个问题.
spring的配置文件
<mongo:db-factory dbname="somedb" host="localhost" port="27017" />
<mongo:mapping-converter id="mongoConverter">
</mongo:mapping-converter>
<bean id="noClassMongoConverter" class="org.devside.mongodb.MongoConverterEnhanceFactoryBean">
<property name="converter" ref="mongoConverter" />
</bean>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mongoConverter" ref="noClassMongoConverter" />
</bean>
这 里关键的类org.devside.mongodb.MongoConverterEnhanceFactoryBean. 其实没做什么特别的事情. 就是把spring-data的MappingMongoConverter拿过来,然后把TypeMapper设置一下.
public class MongoConverterEnhanceFactoryBean implements FactoryBean<MappingMongoConverter> {
private MappingMongoConverter converter;
public void setConverter(MappingMongoConverter converter) {
this.converter = converter;
}
public MappingMongoConverter getObject() throws Exception {
MongoTypeMapper typeMapper = new DefaultMongoTypeMapper(null);
converter.setTypeMapper(typeMapper);
return converter;
}
public Class<?> getObjectType() {
return MappingMongoConverter.class;
}
public boolean isSingleton() {
return true;
}
}
DefaultMongoTypeMapper类的构造函数的第一个参数是Type在MongoDB中名字. 设置为null的话就不会在保存时自动添加_class属性.
具体javadocs看
http://static.springsource.org/spring-data/data-mongo/docs/1.0.0.RELEASE/api/org/springframework/data/mongodb/core/convert/DefaultMongoTypeMapper.html
posted on 2012-03-29 15:20
SIMONE 阅读(680)
评论(0) 编辑 收藏 所属分类:
JAVA