Please use 'MongoMappingContext#setAutoIndexCr

2020-03-25 08:47发布

问题:

I went through https://docs.spring.io/spring-data/mongodb/docs/2.2.0.RC1/reference/html/#mapping-usage and other sources on the web, but the solution did not worked for me.

I am using Spring Boot 2.2.2.RELEASE and Spring Data Mongo. In this example, at Model/Pojo field level We're using

@Indexed(name = AppConstants.FIRSTNAME_INDEX, direction = IndexDirection.ASCENDING)
private String firstName;

Error:

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);
> }
> -----------------------------------------------------------------------------------------

As suggested in the log, I implemented, but I dont see method setAutoIndexCreation.

public class MongoConfig extends AbstractMongoClientConfiguration {

    @Override
    public MongoClient mongoClient() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected String getDatabaseName() {
        // TODO Auto-generated method stub
        return null;
    }
}

回答1:

Disable auto index creation in application.properties file

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

or application.yml file

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

Create the class MongoConfiguration whit @Configuration annotation

Injetc this dependencies

private final MongoTemplate mongoTemplate;
private final MongoConverter mongoConverter;

and add this method

@EventListener(ApplicationReadyEvent.class)
public void initIndicesAfterStartup() {

    log.info("Mongo InitIndicesAfterStartup init");
    var init = System.currentTimeMillis();

    var mappingContext = this.mongoConverter.getMappingContext();

    if (mappingContext instanceof MongoMappingContext) {
        MongoMappingContext mongoMappingContext = (MongoMappingContext) mappingContext;
        for (BasicMongoPersistentEntity<?> persistentEntity : mongoMappingContext.getPersistentEntities()) {
            var clazz = persistentEntity.getType();
            if (clazz.isAnnotationPresent(Document.class)) {
                var resolver = new MongoPersistentEntityIndexResolver(mongoMappingContext);

                var indexOps = mongoTemplate.indexOps(clazz);
                resolver.resolveIndexFor(clazz).forEach(indexOps::ensureIndex);
            }
        }
    }

    log.info("Mongo InitIndicesAfterStartup take: {}", (System.currentTimeMillis() - init));
}

remember that var is only for java 11+

The final class, which uses Lombok

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver;
import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;


@Slf4j
@RequiredArgsConstructor
@Configuration
public class MongoConfiguration {

private final MongoTemplate mongoTemplate;

private final MongoConverter mongoConverter;

@EventListener(ApplicationReadyEvent.class)
public void initIndicesAfterStartup() {

        log.info("Mongo InitIndicesAfterStartup init");
        var init = System.currentTimeMillis();

        var mappingContext = this.mongoConverter.getMappingContext();

        if (mappingContext instanceof MongoMappingContext) {
            MongoMappingContext mongoMappingContext = (MongoMappingContext) mappingContext;
            for (BasicMongoPersistentEntity<?> persistentEntity : mongoMappingContext.getPersistentEntities()) {
                var clazz = persistentEntity.getType();
                if (clazz.isAnnotationPresent(Document.class)) {
                    var resolver = new MongoPersistentEntityIndexResolver(mongoMappingContext);

                    var indexOps = mongoTemplate.indexOps(clazz);
                    resolver.resolveIndexFor(clazz).forEach(indexOps::ensureIndex);
                }
            }
        }

        log.info("Mongo InitIndicesAfterStartup take: {}", (System.currentTimeMillis() - init));
    }

}


回答2:

But the solution doensn't work well, at least within the reactive context. The mongoMappingContext.getPersistentEntities() is empty at this time. Only auto-index-creation: true (or even mongoMappingContext.setAutoIndexCreation(true)) ensure the creation of indexes.



回答3:

tried with the following configuration, I even created an own mappingContext bean

@Configuration
public class MongoConfiguration extends AbstractMongoClientConfiguration {

    private final AbstractCloudConfig abstractCloudConfig;

    @Autowired
    public MongoConfiguration(AbstractCloudConfig abstractCloudConfig) {
        this.abstractCloudConfig = abstractCloudConfig;
    }

    @Override
    public MongoClient mongoClient() {
        return MongoClients.create(MongoClientSettings.builder().build());
    }

    @Bean
    @Override
    public MongoDbFactory mongoDbFactory() {
        return abstractCloudConfig.connectionFactory().mongoDbFactory();
    }

    @Bean
    public MappingMongoConverter mongoConverter(MappingMongoConverter mongoConverter) {
        /*
         * For some obscure reason, Spring Mongo does not like hash maps with keys that contain dots '.'.
         * We configure to replace dots '.' in maps with some obscure character that does not occur in in keys.
         */
        mongoConverter.setMapKeyDotReplacement("~");
        return mongoConverter;
    }

    @Bean
    public MongoMappingContext mongoMappingContext() throws ClassNotFoundException {
        MongoMappingContext mappingContext = new MongoMappingContext();
        mappingContext.setInitialEntitySet(this.getInitialEntitySet());
        mappingContext.setSimpleTypeHolder(this.customConversions().getSimpleTypeHolder());
        mappingContext.setFieldNamingStrategy(this.fieldNamingStrategy());
        mappingContext.setAutoIndexCreation(false);
        return mappingContext;
    }

    @Override
    protected String getDatabaseName() {
        throw new RuntimeException("This method should not be called");
    }

    @EventListener(ApplicationReadyEvent.class)
    public void initIndicesAfterStartup() throws ClassNotFoundException {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
        this.mongoMappingContext().setAutoIndexCreation(false);
        createIndexForEntity(DataSetDefinitionV2.class, mongoTemplate);
        createIndexForEntity(ModelConfiguration.class, mongoTemplate);
        createIndexForEntity(ScheduleEntity.class, mongoTemplate);
    }

    private void createIndexForEntity(Class<?> entityClass, MongoTemplate mongoTemplate) throws ClassNotFoundException {
        IndexOperations indexOps = mongoTemplate.indexOps(entityClass);
        IndexResolver resolver = new MongoPersistentEntityIndexResolver(this.mongoMappingContext());
        resolver.resolveIndexFor(entityClass).forEach(indexOps::ensureIndex);
    }
}

still the warning comes.I event tried spring.data.mongodb.auto-index-creation=false in application.properties, also no luck