java - Spring Boot中未创建MongoDB唯一索引

标签 java spring mongodb spring-boot

在 Spring boot + MongoDB 应用程序中,我尝试为电子邮件字段创建唯一索引。

@Document
public class User {

    @Id
    private String id;

    @Indexed(unique = true)
    private String email;

}
public interface UserRepository extends MongoRepository<User, String>

但我仍然可以使用同一电子邮件插入两个用户对象,因此

userRepository.save(new User("my@email.com"))
userRepository.save(new User("my@email.com"))

在用户集合中创建两个条目。

我做错了什么?

我知道Spring Data MongoDB - Where to create an index programmatically for a Mongo collection? ,但我正在寻找“仅注释”的解决方案。

最佳答案

我引用documentation :

Spring Data MongoDB can automatically create indexes for entity types annotated with @Document. Index creation must be explicitly enabled since version 3.0 to prevent undesired effects with collection lifecycle and performance impact.

您是否启用了自动索引创建?因为如果您不这样做,这很可能就是您的独特约束不被遵守的原因。您可以通过连接到 MongoDB 实例并运行 db.user.getIndexes() 来验证是否不存在索引。这将打印您的用户集合的索引。

使用 Spring Boot,您可以在 application.yml 中使用以下配置启用自动索引创建:

spring:
  data:
    mongodb:
      auto-index-creation: true

或者如果您更喜欢属性:

spring.data.mongodb.auto-index-creation=true

关于java - Spring Boot中未创建MongoDB唯一索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62029674/

相关文章:

mongodb - 寻找引用 nodejs、expressjs 和 mongodb 应用程序用作模板

javascript - 使用 Python 和 MongoDB 进行实时分析

java - 如何在 Eclipse 中创建我自己的实用程序类?

java - 在代理服务器上使用剩余模板时如何避免代理

java - Spring Cloud Feign 客户端重复列表值

mongodb - Grails 3和Mlab MongoDB

java - 用于分析 Java 源代码的工具

java - 将 java 变量传递给 sql (netbeans)

java - 使用 Java SE 的 JPA : javax. persistence.PersistenceException:没有 EntityManager 的持久性提供程序

java - Spring - 让 TaskExecutor 和 TaskScheduler 由同一线程池支持