diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoConfigurationSupport.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoConfigurationSupport.java
index 41870bdca..9b094e537 100644
--- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoConfigurationSupport.java
+++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoConfigurationSupport.java
@@ -200,7 +200,7 @@ public abstract class MongoConfigurationSupport {
* {@link org.springframework.data.mongodb.core.index.IndexDefinition} from the entity or not.
*
* @return {@literal false} by default.
- * INFO: As of 3.x the default will is set to {@literal false} was {@literal true} in 2.x.
+ * INFO: As of 3.x the default is set to {@literal false}; In 2.x it was {@literal true}.
* @since 2.2
*/
protected boolean autoIndexCreation() {
diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/JustOnceLogger.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/JustOnceLogger.java
deleted file mode 100644
index 109270ec0..000000000
--- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/JustOnceLogger.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright 2019-2020 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.springframework.data.mongodb.core.index;
-
-import java.util.Collections;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentSkipListSet;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author Christoph Strobl
- * @since 2.2
- */
-class JustOnceLogger {
-
- private static final Map> KNOWN_LOGS = new ConcurrentHashMap<>();
- private static final String AUTO_INDEX_CREATION_CONFIG_CHANGE;
-
- static {
- AUTO_INDEX_CREATION_CONFIG_CHANGE = "Automatic index creation will be disabled by default as of Spring Data MongoDB 3.x."
- + System.lineSeparator()
- + "\tPlease use 'MongoMappingContext#setAutoIndexCreation(boolean)' or override 'MongoConfigurationSupport#autoIndexCreation()' to be explicit."
- + System.lineSeparator()
- + "\tHowever, we recommend setting up indices manually in an application ready block. You may use index derivation there as well."
- + System.lineSeparator() + System.lineSeparator() //
- + "\t> -----------------------------------------------------------------------------------------"
- + System.lineSeparator() //
- + "\t> @EventListener(ApplicationReadyEvent.class)" + System.lineSeparator() //
- + "\t> public void initIndicesAfterStartup() {" + System.lineSeparator() //
- + "\t>" + System.lineSeparator() //
- + "\t> IndexOperations indexOps = mongoTemplate.indexOps(DomainType.class);" + System.lineSeparator()//
- + "\t>" + System.lineSeparator() //
- + "\t> IndexResolver resolver = new MongoPersistentEntityIndexResolver(mongoMappingContext);"
- + System.lineSeparator() //
- + "\t> resolver.resolveIndexFor(DomainType.class).forEach(indexOps::ensureIndex);" + System.lineSeparator() //
- + "\t> }" + System.lineSeparator() //
- + "\t> -----------------------------------------------------------------------------------------"
- + System.lineSeparator();
- }
-
- static void logWarnIndexCreationConfigurationChange(String loggerName) {
- warnOnce(loggerName, AUTO_INDEX_CREATION_CONFIG_CHANGE);
- }
-
- static void warnOnce(String loggerName, String message) {
-
- Logger logger = LoggerFactory.getLogger(loggerName);
- if (!logger.isWarnEnabled()) {
- return;
- }
-
- if (!KNOWN_LOGS.containsKey(loggerName)) {
-
- KNOWN_LOGS.put(loggerName, new ConcurrentSkipListSet<>(Collections.singleton(message)));
- logger.warn(message);
- } else {
-
- Set messages = KNOWN_LOGS.get(loggerName);
- if (messages.contains(message)) {
- return;
- }
-
- messages.add(message);
- logger.warn(message);
- }
- }
-}
diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreator.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreator.java
index ec910a868..172c10590 100644
--- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreator.java
+++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreator.java
@@ -139,8 +139,6 @@ public class MongoPersistentEntityIndexCreator implements ApplicationListener createIndex(IndexDefinitionHolder indexDefinition) {
- JustOnceLogger.logWarnIndexCreationConfigurationChange(this.getClass().getName());
-
return operationsProvider.indexOps(indexDefinition.getCollection()).ensureIndex(indexDefinition) //
.onErrorResume(ReactiveMongoPersistentEntityIndexCreator::isDataIntegrityViolation,
e -> translateException(e, indexDefinition));
diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/MongoMappingContext.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/MongoMappingContext.java
index 170ba47d7..239fb4b1c 100644
--- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/MongoMappingContext.java
+++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/MongoMappingContext.java
@@ -42,7 +42,6 @@ public class MongoMappingContext extends AbstractMappingContext> for further details.
+* <> is now **disabled** by default.
* Support for <>.
* Removal of `_id` flattening for composite Id's when using `MongoTemplate` aggregations.
* Apply pagination when using GridFS `find(Query)`.
diff --git a/src/main/asciidoc/reference/mapping.adoc b/src/main/asciidoc/reference/mapping.adoc
index eb690a34d..8e2736f2c 100644
--- a/src/main/asciidoc/reference/mapping.adoc
+++ b/src/main/asciidoc/reference/mapping.adoc
@@ -390,6 +390,64 @@ public class Person {
IMPORTANT: The `@Id` annotation tells the mapper which property you want to use for the MongoDB `_id` property, and the `@Indexed` annotation tells the mapping framework to call `createIndex(…)` on that property of your document, making searches faster.
Automatic index creation is only done for types annotated with `@Document`.
+[[mapping.index-creation]]
+=== Index Creation
+
+Spring Data MongoDB can automatically create indexes for entity types annotated with `@Document`. Index creation must be explicitly enabled since version 3.0 to prevent undesired effects with collection lifecyle and performance impact. Indexes are automatically created for the initial entity set on application startup and when accessing an entity type for the first time while the application runs.
+
+We generally recommend explicit index creation for application-based control of indexes as Spring Data cannot automatically create indexes for collections that were recreated while the application was running.
+
+`IndexResolver` provides an abstraction for programmatic index definition creation if you want to make use of `@Indexed` annotations such as `@GeoSpatialIndexed`, `@TextIndexed`, `@CompoundIndex`. You can use index definitions with `IndexOperations` to create indexes. A good point in time for index creation is on application startup, specifically after the application context was refreshed, triggered by observing `ContextRefreshedEvent`. This event guarantees that the context is fully initialized. Note that at this time other components, especially bean factories might have access to the MongoDB database.
+
+.Programmatic Index Creation for a single Domain Type
+====
+[source,java]
+----
+class MyListener {
+
+ @EventListener(ContextRefreshedEvent.class)
+ public void initIndicesAfterStartup() {
+
+ MappingContext extends MongoPersistentEntity>, MongoPersistentProperty> mappingContext = mongoTemplate
+ .getConverter().getMappingContext();
+
+ IndexResolver resolver = new MongoPersistentEntityIndexResolver(mappingContext);
+
+ IndexOperations indexOps = mongoTemplate.indexOps(DomainType.class);
+ resolver.resolveIndexFor(DomainType.class).forEach(indexOps::ensureIndex);
+ }
+}
+----
+====
+
+.Programmatic Index Creation for all Initial Entities
+====
+[source,java]
+----
+class MyListener{
+
+ @EventListener(ContextRefreshedEvent.class)
+ public void initIndicesAfterStartup() {
+
+ MappingContext extends MongoPersistentEntity>, MongoPersistentProperty> mappingContext = mongoTemplate
+ .getConverter().getMappingContext();
+
+ // consider only entities that are annotated with @Document
+ mappingContext.getPersistentEntities()
+ .stream()
+ .filter(it -> it.isAnnotationPresent(Document.class))
+ .forEach(it -> {
+
+ IndexOperations indexOps = mongoTemplate.indexOps(it.getType());
+ resolver.resolveIndexFor(it.getType()).forEach(indexOps::ensureIndex);
+ });
+ }
+}
+----
+====
+
+Alternatively, if you want to ensure index and collection presence before any component is able to access your database from your application, declare a `@Bean` method for `MongoTemplate` and include the code from above before returning the `MongoTemplate` object.
+
[NOTE]
====
To turn automatic index creation _ON_ please override `autoIndexCreation()` in your configuration.
@@ -403,14 +461,12 @@ public class Config extends AbstractMongoClientConfiguration {
return true;
}
- // ...
+// ...
}
----
====
-IMPORTANT: Automatic index creation is turned _OFF_ by default as of the release of 3.x.
-We recommend index creation to happen either out of band or as part of the application startup using
-`IndexOperations`.
+IMPORTANT: Automatic index creation is turned _OFF_ by default as of version 3.0.
[[mapping-usage-annotations]]
=== Mapping Annotation Overview
diff --git a/src/main/asciidoc/upgrading.adoc b/src/main/asciidoc/upgrading.adoc
index f695e0d06..c89376607 100644
--- a/src/main/asciidoc/upgrading.adoc
+++ b/src/main/asciidoc/upgrading.adoc
@@ -151,6 +151,7 @@ Element | Comment
=== Auto Index Creation
Annotation based index creation is now turned **OFF** by default and needs to be enabled eg. when relying on `@GeoSpatialIndexed`.
+Please refer to <> on how to create indexes programmatically.
.Enable Auto Index Creation
====
@@ -158,7 +159,7 @@ Annotation based index creation is now turned **OFF** by default and needs to be
.XML Namespace
[source,xml]
----
- <1>
+ <1>
----
.Java Config
@@ -168,7 +169,7 @@ Annotation based index creation is now turned **OFF** by default and needs to be
public class Config extends AbstractMongoClientConfiguration {
@Override
- protected boolean autoIndexCreation() { <2>
+ protected boolean autoIndexCreation() { <2>
return true;
}
@@ -183,14 +184,14 @@ MongoDatabaseFactory dbFactory = new SimpleMongoClientDatabaseFactory(...);
DefaultDbRefResolver dbRefResolver = new DefaultDbRefResolver(dbFactory);
MongoMappingContext mappingContext = new MongoMappingContext();
-mappingContext.setAutoIndexCreation(true); <3>
+mappingContext.setAutoIndexCreation(true); <3>
// ...
mappingContext.afterPropertiesSet();
MongoTemplate template = new MongoTemplate(dbFactory, new MappingMongoConverter(dbRefResolver, mappingContext));
----
<1> Use the XML namespace attribute `auto-index-creation` on `mapping-converter`.
-<2> Overrride `autoIndexCreation` via `AbstractMongoClientConfiguration` or `AbstractReactiveMongoClientConfiguration`.
+<2> Override `autoIndexCreation` via `AbstractMongoClientConfiguration` or `AbstractReactiveMongoClientConfiguration`.
<3> Set the flag on `MongoMappingContext`.
====