根context.xml中:
<mongo:mongo id="mongo" host="localhost" port="27017" />
<mongo:db-factory dbname="meraComputer" mongo-ref="mongo" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<bean id="userDaoImpl" class="net.meraComputer.spring.daoImpl.UserDaoImpl">
<property name="mongoTemplate" ref="mongoTemplate"/>
</bean>
在UserDAOImpl:
private MongoTemplate mongoTemplate;
@Required
public void setMongoTemplate(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
@Override
public void saveUser(UserAccount user) {
if(mongoTemplate.collectionExists("userAccount")) {
mongoTemplate.save(user);
}else {
mongoTemplate.createCollection("userAccount");
mongoTemplate.save(user);
}
}
我在保存第一个UserAccount时已经创建了userAccount集合。
db.userAccount.find().pretty()
{
"_id" : ObjectId("568781929a0085d703e45e0e"),
"_class" : "net.meraComputer.spring.model.UserAccount",
"username" : "Test",
"password" : "$2a$10$XrDNeBw0vKTr0zEXVVLMy.N2L4wEzJ/C1lBAuvRQB6YC6EMFr3ws6",
"firstname" : "Test",
"lastname" : "Test",
"userRole" : [ ],
"roles" : [
DBRef("role", "ADMIN")
]
但是当我尝试修复另一个用户时,它只是在这里返回false mongoTemplate.collectionExists("userAccount")
,当它转到保存部分时会引发异常:
org.springframework.data.mongodb.UncategorizedMongoDbException: command failed [create]: { "serverUsed" : "localhost/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "collection already exists" , "code" : 48}; nested exception is com.mongodb.CommandResult$CommandFailure: command failed [create]: { "serverUsed" : "localhost/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "collection already exists" , "code" : 48}
org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:78)
org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:1800)
org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:388)
org.springframework.data.mongodb.core.MongoTemplate.doCreateCollection(MongoTemplate.java:1413)
我试过了:
mongoTemplate.getCollectionNames() - no result.
mongoTemplate.collectionExists(UserAccount.class) - false
答案 0 :(得分:1)
将我的依赖项更改为以下内容解决了我的问题:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>1.8.2.RELEASE</version>
</dependency>