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

Meh*_*lik 4 java exception mongodb spring-data-mongodb spring-boot

我正在使用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;
Run Code Online (Sandbox Code Playgroud)

当有任何重复的名称或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)
Run Code Online (Sandbox Code Playgroud)

我们如何获得抛出异常的密钥.

像我们放置@NotNull(message = "Product briefDescription cannot be null")一些文件时它会给你message的内容exception,但是没有注释message属性@Indexed.

有办法吗?

hel*_*lmy 8

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

不幸的是,你必须从消息中解析出这些信息.这种限制已在其他地方提出:

在Mongo中可靠地检索哪个字段引发了"重复键错误"

并在以下JIRA门票中:

但是,在您的示例中(副本为null),我强烈建议您在客户端级别尽可能多地进行验证,而不是依赖数据库来处理可在客户端完成的任何验证.