java - 如何在 spring-data-mongodb 中获取失败的@Indexed(unique=true)

标签 java mongodb exception spring-boot spring-data-mongodb

我正在使用 Spring-Boot 1.5.1MongoDB 3.4.6

我有一个 MongoDB 文档,它在某些字段上有一些 @Indexed(unique=true) 注释。

@Document(collection="Product")
public class Product{
    @Id
    private String id;
    @Indexed(unique=true)
    private String name;
    @Indexed(unique=true)
    private String searchName;

当有任何重复的名称或搜索名称时,它会抛出 org.springframework.dao.DuplicateKeyException

堆栈跟踪:

Caused by: org.springframework.dao.DuplicateKeyException: E11000 duplicate key error index: Product.name  dup key: { : "name" }; nested exception is com.mongodb.MongoException$DuplicateKey: E11000 duplicate key error index: Product.name dup key: { : "name" }
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:52)

我们如何获取抛出异常的键。

类似于当我们将 @NotNull(message = "Product briefDescription cannot be null") 放在某些字段上时,它会在 exception 中为您提供 message ,但是 @Indexed 注释没有 message 属性。

有什么办法吗?

最佳答案

异常消息包含您要求的信息,它包括引发错误的索引的名称(在您的情况下为 Product.nameProduct. searchName).

不幸的是,您必须从消息中解析出该信息。此限制已在其他地方提出:

Robustly retrieve which field caued 'duplicate key error' in Mongo

在以下 JIRA 票证中:

但是,在您的示例中(重复项为空),我强烈建议您将尽可能多的验证推到客户端级别,而不是依赖数据库来处理可以在客户。

关于java - 如何在 spring-data-mongodb 中获取失败的@Indexed(unique=true),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46387252/

相关文章:

java - 是否可以避免将对象声明为final?

javascript - 在 mongodb(数据库部分)与 Node js(服务器端?

c++ - 访问内存中不存在的数组索引的正确异常类型?

python - 无法在 Python 中中止 (ctrl+c)

java - 了解收件箱的发送方法

Java 相当于 Ruby 的 `code if condition`

Mongodb Atlas连接问题

node.js - 如何使用 $filter(aggregation) 仅在条件为 true 时选择数组的某些字段?

exception - ERROR_DLL_INIT_FAILED 是什么意思?

java - 从文本文件读入,有字符限制