Springboot集成spring-data-mongodb的 @Indexed注解无效问题

spring-data中的注解org.springframework.data.mongodb.core.index.Indexed添加到字段上后,在通过该实体类操作集合时可以自动创建索引,即使集合已经存在也可以创建索引,对内嵌文档同样有效,但是将注解删除后索引不会一同删除。

但是有时索引不会自动创建,此时有以下几种可能:

  1. 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
  1. 添加了auto-index-creation但是不生效
    检查是否同时存在其他java配置类和配置文件,若有,改为java配置
public class MongoConfig extends AbstractMongoClientConfiguration {

    // rest of the config goes here

    @Override
    protected boolean autoIndexCreation() {
        return true;
    }
}
  1. 实体类未添加@Document注解
    必须要有@Document注解且在注解中指定了集合的名称才会生效

posted on 2022-11-09 15:39  shangtx0  阅读(1604)  评论(0)    收藏  举报

导航