spring-data中的注解org.springframework.data.mongodb.core.index.Indexed添加到字段上后,在通过该实体类操作集合时可以自动创建索引,即使集合已经存在也可以创建索引,对内嵌文档同样有效,但是将注解删除后索引不会一同删除。
但是有时索引不会自动创建,此时有以下几种可能:
- spring-boot设置中未将auto-index-creation设为true, 从Spring Data MongoDB 3.0以后,出于防止滥用的考虑,自动创建索引是默认关闭的,需要设置开启。
properties
spring.data.mongodb.auto-index-creation=true
yaml
spring:
data:
mongodb:
auto-index-creation: true
- 添加了auto-index-creation但是不生效
检查是否同时存在其他java配置类和配置文件,若有,改为java配置
public class MongoConfig extends AbstractMongoClientConfiguration {
// rest of the config goes here
@Override
protected boolean autoIndexCreation() {
return true;
}
}
- 实体类未添加@Document注解
必须要有@Document注解且在注解中指定了集合的名称才会生效