关于Spring Data MongoDB @Indexed出错

今天使用MongoDB给字段加索引的时候用的是@Indexed 注解,本以为会自动创建索引,结果出错了,部分日志信息如下。

2020-02-19 18:40:13.865  WARN 11552 --- [           main] .m.c.i.MongoPersistentEntityIndexCreator : Automatic index creation will be disabled by default as of Spring Data MongoDB 3.x.

	Please use 'MongoMappingContext#setAutoIndexCreation(boolean)' or override 'MongoConfigurationSupport#autoIndexCreation()' to be explicit.
	However, we recommend setting up indices manually in an application ready block. You may use index derivation there as well.

	> -----------------------------------------------------------------------------------------
	> @EventListener(ApplicationReadyEvent.class)
	> public void initIndicesAfterStartup() {
	>
	>     IndexOperations indexOps = mongoTemplate.indexOps(DomainType.class);
	>
	>     IndexResolver resolver = new MongoPersistentEntityIndexResolver(mongoMappingContext);
	>     resolver.resolveIndexFor(DomainType.class).forEach(indexOps::ensureIndex);
	> }
	> -----------------------------------------------------------------------------------------

日志中说的很明白了,并给了例子。Spring Data MongoDB3.X 后的版本不再支持自动创建索引,如果要坚持使用@Indexed注解需要额外的设置,并建议我们在手动创建索引。
按照提示,例子如下:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {
    private Long id;
    private Integer age;
    private String username;
}



@Configuration
public class MongoDbConfig {
    final MongoTemplate mongoTemplate;
    public MongoDbConfig(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void initIndicesAfterStartup() {
        mongoTemplate.indexOps(User.class).ensureIndex(new Index().on("age", Sort.Direction.ASC));
        
    }
}

IndexOperations. ensureIndex

	/**
	 * Ensure that an index for the provided {@link IndexDefinition} exists for the collection indicated by the entity
	 * class. If not it will be created.
	 *
	 * @param indexDefinition must not be {@literal null}.
	 */
	String ensureIndex(IndexDefinition indexDefinition);

文档中说明确认IndexDefinition中所确定的索引,如果不存在将会被创建。

你可能感兴趣的:(spring,data)