我正在使用mongoRepository.save(),但是当重复项阻止插入时无法获取错误信息。 作为测试我插入一个重复的用户名和mongo只是忽略它。但是当用户名是唯一的时,它会按预期插入。
请参阅下面的服务类:
package com.onlinedateshow.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.mongodb.BasicDBObject;
import com.onlinedateshow.data.model.User;
import com.onlinedateshow.data.repo.user.UserRepository;
import com.onlinedateshow.model.ui.RegisterUI;
import com.onlinedateshow.model.util.RegisterMapper;
@Service
public class RegisterService {
@Autowired
private UserRepository userRepo;
@Autowired
MongoTemplate template;
public String addUser(RegisterUI registerData) {
User newUser = RegisterMapper.toPersistenceBean(registerData);
try{
//does not return error, if duplicates are found, silently
//ignores the query
User saveduser = userRepo.save(newUser);
//below is what I want but don't know how to get it from a repository
//String error = template.getDb().getLastError().getErrorMessage();
//return error;
return null;
}catch(Exception e){
return e.getLocalizedMessage();
}
}
}
这是我的UserRepository接口:
package com.onlinedateshow.data.repo.user;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.onlinedateshow.data.model.User;
public interface UserRepository extends MongoRepository<User, String>,
PagingAndSortingRepository<User, String> {
User findByEmail(String email);
User findById(String id);
User findByUserName(String userName);
}
这是我设置MongoDbFactory的XML文件:
<!-- Activate Spring Data MongoDB repository support -->
<mongo:repositories base-package="com.mydata.repo.user" />
<!-- MongoDB host -->
<mongo:mongo host="${mongo.host.name}" port="${mongo.host.port}" />
<mongo:db-factory dbname="${mongo.db.name}" />
<!-- Template for performing MongoDB operations -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"
c:mongo-ref="mongo" c:databaseName="${mongo.db.name}" />