我正在使用 Spring-Boot 1.5.1
和 MongoDB 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.name
或 Product. 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/