0
使用Spring MVC和Spring數據的MongoDB連接的MongoDB數據庫 這是我的示例代碼我的項目:自定義映射Spring MVC的,春天數據MongoDB的
public class Data extends BasicDBObject{
@Id
public String id;
@Transient
public String obName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getObName() {
return obName;
}
public void setObName(String obName) {
this.obName = obName;
}
}
自定義轉換器
@ReadingConverter
public class DataReadConverter implements Converter<BasicDBObject, Data>{
/* (non-Javadoc)
* @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object)
*/
@Override
public Data convert(BasicDBObject source) {
Data data = new Data();
data.setId((ObjectId) source.get("_id"));
data.putAll(source.toMap());
return data;
}
}
註冊轉換器
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- MongoDB Config -->
<mongo:mongo host="localhost" port="27017" />
<mongo:db-factory dbname="opmdrive" mongo-ref="mongo"/>
<mongo:mapping-converter base-package="com.chick.opm.model.object">
<mongo:custom-converters>
<mongo:converter>
<bean class="com.chick.opm.spring.DataReadConverter"/>
</mongo:converter>
<mongo:converter>
<bean class="com.chick.opm.spring.DataWriteConverter"/>
</mongo:converter>
</mongo:custom-converters>
</mongo:mapping-converter>
<bean id="mongoOperation" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mongoConverter" ref="mappingConverter"/>
</bean>
<bean class="org.springframework.data.mongodb.core.mapping.event.LoggingEventListener"/>
獲取數據和測繪
List<Data> updatedUser = getCurrentMongoOperations().findAll(Data.class, "accounts");
System.out.println(updatedUser.get(0).getId().toStringMongod());
return updatedUser;
實際結果
錯誤不能施放BasicDBObject到數據
期待導致
[
{
"id": "5820428b1a82a72dfce0c914",
"username": 17671794,
"password": "mypassword"
},
{
"id": "5820428d1a82a72dfce0c915",
"username": 81964940,
"password": "mypassword"
},
{
"id": "5822a7e642af5424d0bb07ab",
"username": 75165254,
"password": "mypassword"
}
]
您可以添加堆棧跟蹤的錯誤? – Veeram