Created
September 13, 2020 07:44
-
-
Save oharsta/7a88e3efb91f8749c6e777116a449db8 to your computer and use it in GitHub Desktop.
Ensure all annotated indexes on @document models are created in MongoDB after application startup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import lombok.SneakyThrows; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.context.event.ApplicationReadyEvent; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.context.event.EventListener; | |
import org.springframework.data.mongodb.core.MongoTemplate; | |
import org.springframework.data.mongodb.core.convert.MappingMongoConverter; | |
import org.springframework.data.mongodb.core.index.IndexOperations; | |
import org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver; | |
import org.springframework.data.mongodb.core.mapping.Document; | |
import org.springframework.data.mongodb.core.mapping.MongoMappingContext; | |
@Configuration | |
public class MongoIndexConfiguration { | |
private final MappingMongoConverter mongoConverter; | |
private final MongoTemplate mongoTemplate; | |
@Autowired | |
public MongoConverter(MappingMongoConverter mongoConverter, MongoTemplate mongoTemplate) { | |
this.mongoConverter = mongoConverter; | |
this.mongoTemplate = mongoTemplate; | |
} | |
@SneakyThrows | |
@EventListener(ApplicationReadyEvent.class) | |
public void initIndicesAfterStartup() { | |
mongoConverter.setMapKeyDotReplacement("@"); | |
MongoMappingContext mappingContext = (MongoMappingContext) this.mongoConverter.getMappingContext(); | |
MongoPersistentEntityIndexResolver resolver = new MongoPersistentEntityIndexResolver(mappingContext); | |
mappingContext.getPersistentEntities().forEach(persistentEntity -> { | |
Class<?> clazz = persistentEntity.getType(); | |
if (clazz.isAnnotationPresent(Document.class)) { | |
IndexOperations indexOps = mongoTemplate.indexOps(clazz); | |
resolver.resolveIndexFor(clazz).forEach(indexOps::ensureIndex); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment