gpt4 book ai didi

java - MongoTemplate 插入状态

转载 作者:行者123 更新时间:2023-11-30 07:07:44 25 4
gpt4 key购买 nike

我想创建一个 DAO,将用户保存到我的数据库中。他们应该有唯一的登录名,这有点问题,因为 mongo db 没有事务。我有一个类,其中的用户如下所示:

@Document(collection = "users")
public class User {

@Id
private String id;

@Indexed(unique = true)
private String username;

... }

在我的 DAO 中我想保存新用户

mongoTemplate.insert(user);

但是我如何获得结果以将响应发送到我的前端,无论用户创建是否成功?

最佳答案

当唯一索​​引被违反时,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}

关于java - MongoTemplate 插入状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39798877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com