調用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