我想要创建一个DAO,将用户保存到我的数据库中。它们应该有唯一的登录,这有点问题,因为mongo没有事务。我有一个用户类,如下所示:
@Document(collection = "users")
public class User {
@Id
private String id;
@Indexed(unique = true)
private String username;
... }在我的DAO中,我想保存新用户
mongoTemplate.insert(user);但是,如何才能得到结果来向我的前端发送响应--用户创建是否成功?
发布于 2016-09-30 22:05:30
当违反唯一索引时,API将抛出org.springframework.dao.DuplicateKeyException。
示例代码:-
try {
mongoOperations.insert(order);
} catch (DuplicateKeyException de) {
de.printStackTrace();
}违反唯一索引时的异常消息:-
org.springframework.dao.DuplicateKeyException: { "serverUsed" : "127.0.0.1:27017" , "ok" : 1 , "n" : 0 , "err" : "E11000 duplicate key error collection: localhost.order index: user_1 dup key: { : \"good\" }" , "code" : 11000}; nested exception is com.mongodb.MongoException$DuplicateKey: { "serverUsed" : "127.0.0.1:27017" , "ok" : 1 , "n" : 0 , "err" : "E11000 duplicate key error collection: localhost.order index: user_1 dup key: { : \"good\" }" , "code" : 11000}https://stackoverflow.com/questions/39798877
复制相似问题