spring mongodb中去掉_class列_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > spring mongodb中去掉_class列

spring mongodb中去掉_class列

 2012/10/15 10:38:17  jackyrong  程序员俱乐部  我要评论(0)
  • 摘要:在springformongodb中,会发现当一个pojo序列化为一个document时,会出现如下情况:publicclassUser{Stringusername;Stringpassword;}转变为mongodb时MongoOperationsmongoOperation=(MongoOperations)ctx.getBean("mongoTemplate");Useruser=newUser("abc","password123");mongoOperation.save(user
  • 标签:Spring MongoDB
在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>




上一篇: java大门 下一篇: bundle命令
发表评论
用户名: 匿名