在 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/