@ -3,7 +3,8 @@ Mark Pollack; Thomas Risberg; Oliver Gierke; Costin Leau; Jon Brisbin; Thomas Da
@@ -3,7 +3,8 @@ Mark Pollack; Thomas Risberg; Oliver Gierke; Costin Leau; Jon Brisbin; Thomas Da
MongoDB supports storing binary files inside its filesystem, GridFS. Spring Data MongoDB provides a `GridFsOperations` interface as well as the corresponding implementation, `GridFsTemplate`, to let you interact with the filesystem. You can set up a `GridFsTemplate` instance by handing it a `MongoDatabaseFactory` as well as a `MongoConverter`, as the following example shows:
.JavaConfig setup for a GridFsTemplate
====
[source,java]
.Java
[source,java,role="primary"]
----
class GridFsConfiguration extends AbstractMongoClientConfiguration {
@ -17,13 +18,9 @@ class GridFsConfiguration extends AbstractMongoClientConfiguration {
@@ -17,13 +18,9 @@ class GridFsConfiguration extends AbstractMongoClientConfiguration {
@ -266,11 +266,11 @@ calling `get()` before the actual conversion
@@ -266,11 +266,11 @@ calling `get()` before the actual conversion
Unless explicitly configured, an instance of `MappingMongoConverter` is created by default when you create a `MongoTemplate`. You can create your own instance of the `MappingMongoConverter`. Doing so lets you dictate where in the classpath your domain classes can be found, so that Spring Data MongoDB can extract metadata and construct indexes. Also, by creating your own instance, you can register Spring converters to map specific classes to and from the database.
You can configure the `MappingMongoConverter` as well as `com.mongodb.client.MongoClient` and MongoTemplate by using either Java-based or XML-based metadata. The following example uses Spring's Java-based configuration:
You can configure the `MappingMongoConverter` as well as `com.mongodb.client.MongoClient` and MongoTemplate by using either Java-based or XML-based metadata. The following example shows the configuration:
.@Configuration class to configure MongoDB mapping support
====
[source,java]
.Java
[source,java,role="primary"]
----
@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {
@ -299,24 +299,11 @@ public class MongoConfig extends AbstractMongoClientConfiguration {
@@ -299,24 +299,11 @@ public class MongoConfig extends AbstractMongoClientConfiguration {
return new LoggingEventListener<MongoMappingEvent>();
}
}
----
<1> The mapping base package defines the root path used to scan for entities used to pre initialize the `MappingContext`. By default the configuration classes package is used.
<2> Configure additional custom converters for specific domain types that replace the default mapping procedure for those types with your custom implementation.
====
`AbstractMongoClientConfiguration` requires you to implement methods that define a `com.mongodb.client.MongoClient` as well as provide a database name. `AbstractMongoClientConfiguration` also has a method named `getMappingBasePackage(…)` that you can override to tell the converter where to scan for classes annotated with the `@Document` annotation.
You can add additional converters to the converter by overriding the `customConversionsConfiguration` method.
MongoDB's native JSR-310 support can be enabled through `MongoConverterConfigurationAdapter.useNativeDriverJavaTimeCodecs()`.
Also shown in the preceding example is a `LoggingEventListener`, which logs `MongoMappingEvent` instances that are posted onto Spring's `ApplicationContextEvent` infrastructure.
NOTE: `AbstractMongoClientConfiguration` creates a `MongoTemplate` instance and registers it with the container under the name `mongoTemplate`.
Spring's MongoDB namespace lets you enable mapping functionality in XML, as the following example shows:
@ -353,8 +340,19 @@ Spring's MongoDB namespace lets you enable mapping functionality in XML, as the
@@ -353,8 +340,19 @@ Spring's MongoDB namespace lets you enable mapping functionality in XML, as the
</beans>
----
<1> The mapping base package defines the root path used to scan for entities used to pre initialize the `MappingContext`. By default the configuration classes package is used.
<2> Configure additional custom converters for specific domain types that replace the default mapping procedure for those types with your custom implementation.
====
`AbstractMongoClientConfiguration` requires you to implement methods that define a `com.mongodb.client.MongoClient` as well as provide a database name. `AbstractMongoClientConfiguration` also has a method named `getMappingBasePackage(…)` that you can override to tell the converter where to scan for classes annotated with the `@Document` annotation.
You can add additional converters to the converter by overriding the `customConversionsConfiguration` method.
MongoDB's native JSR-310 support can be enabled through `MongoConverterConfigurationAdapter.useNativeDriverJavaTimeCodecs()`.
Also shown in the preceding example is a `LoggingEventListener`, which logs `MongoMappingEvent` instances that are posted onto Spring's `ApplicationContextEvent` infrastructure.
NOTE: `AbstractMongoClientConfiguration` creates a `MongoTemplate` instance and registers it with the container under the name `mongoTemplate`.
The `base-package` property tells it where to scan for classes annotated with the `@org.springframework.data.mongodb.core.mapping.Document` annotation.
[[mapping-usage]]
@ -607,7 +605,7 @@ The mapping subsystem allows the customization of the object construction by ann
@@ -607,7 +605,7 @@ The mapping subsystem allows the customization of the object construction by ann
* If a parameter is annotated with the `@Value` annotation, the given expression is evaluated and the result is used as the parameter value.
* If the Java type has a property whose name matches the given field of the input document, then it's property information is used to select the appropriate constructor parameter to pass the input field value to. This works only if the parameter name information is present in the java `.class` files which can be achieved by compiling the source with debug information or using the new `-parameters` command-line switch for javac in Java 8.
* Otherwise a `MappingException` will be thrown indicating that the given constructor parameter could not be bound.
* Otherwise, a `MappingException` will be thrown indicating that the given constructor parameter could not be bound.
Since Spring Data MongoDB 1.4, auditing can be enabled by annotating a configuration class with the `@EnableMongoAuditing` annotation, as the followign example shows:
Since Spring Data MongoDB 1.4, auditing can be enabled by annotating a configuration class with the `@EnableMongoAuditing` annotation, as the following example shows:
.Activating auditing using JavaConfig
====
[source,java]
.Java
[source,java,role="primary"]
----
@Configuration
@EnableMongoAuditing
@ -17,19 +17,16 @@ class Config {
@@ -17,19 +17,16 @@ class Config {
}
}
----
====
If you expose a bean of type `AuditorAware` to the `ApplicationContext`, the auditing infrastructure picks it up automatically and uses it to determine the current user to be set on domain types. If you have multiple implementations registered in the `ApplicationContext`, you can select the one to be used by explicitly setting the `auditorAwareRef` attribute of `@EnableMongoAuditing`.
To activate auditing functionality via XML, add the Spring Data Mongo `auditing` namespace element to your configuration, as the following example shows:
If you expose a bean of type `AuditorAware` to the `ApplicationContext`, the auditing infrastructure picks it up automatically and uses it to determine the current user to be set on domain types. If you have multiple implementations registered in the `ApplicationContext`, you can select the one to be used by explicitly setting the `auditorAwareRef` attribute of `@EnableMongoAuditing`.
To enable auditing, leveraging a reactive programming model, use the `@EnableReactiveMongoAuditing` annotation. +
If you expose a bean of type `ReactiveAuditorAware` to the `ApplicationContext`, the auditing infrastructure picks it up automatically and uses it to determine the current user to be set on domain types. If you have multiple implementations registered in the `ApplicationContext`, you can select the one to be used by explicitly setting the `auditorAwareRef` attribute of `@EnableReactiveMongoAuditing`.
@ -82,7 +82,7 @@ Use the `@Meta` annotation to set those options via `maxExecutionTimeMs`, `comme
@@ -82,7 +82,7 @@ Use the `@Meta` annotation to set those options via `maxExecutionTimeMs`, `comme
[source,java]
----
public interface PersonRepository extends CrudReppsitory<Person, String> {
@ -99,7 +99,7 @@ Or use `@Meta` to create your own annotation as shown in the sample below.
@@ -99,7 +99,7 @@ Or use `@Meta` to create your own annotation as shown in the sample below.
@Meta(allowDiskUse = true)
@interface AllowDiskUse { }
public interface PersonRepository extends CrudReppsitory<Person, String> {
@ -51,14 +51,14 @@ Right now this interface serves only to provide type information, but we can add
@@ -51,14 +51,14 @@ Right now this interface serves only to provide type information, but we can add
To start using the repository, use the `@EnableMongoRepositories` annotation.
That annotation carries the same attributes as the namespace element.
If no base package is configured, the infrastructure scans the package of the annotated configuration class.
The following example shows how to use Java configuration for a repository:
The following example shows how to configuration your application to use MongoDB repositories:
@ -113,14 +109,14 @@ Consequently, accessing the second page of `Person` objects at a page size of 10
@@ -113,14 +109,14 @@ Consequently, accessing the second page of `Person` objects at a page size of 10
@ -321,7 +321,8 @@ The code in bold highlights the use of `SimpleMongoClientDbFactory` and is the o
@@ -321,7 +321,8 @@ The code in bold highlights the use of `SimpleMongoClientDbFactory` and is the o
NOTE: Use `SimpleMongoClientDbFactory` when choosing `com.mongodb.client.MongoClient` as the entrypoint of choice.
[[mongo.mongo-db-factory-java]]
=== Registering a `MongoDatabaseFactory` Instance by Using Java-based Metadata
[[mongo.mongo-db-factory.config]]
=== Registering a `MongoDatabaseFactory`
To register a `MongoDatabaseFactory` instance with the container, you write code much like what was highlighted in the previous code listing. The following listing shows a simple example:
@ -330,7 +331,8 @@ To register a `MongoDatabaseFactory` instance with the container, you write code
@@ -330,7 +331,8 @@ To register a `MongoDatabaseFactory` instance with the container, you write code
@Configuration
public class MongoConfiguration {
public @Bean MongoDatabaseFactory mongoDatabaseFactory() {
@Bean
public MongoDatabaseFactory mongoDatabaseFactory() {
return new SimpleMongoClientDatabaseFactory(MongoClients.create(), "database");
}
}
@ -338,7 +340,9 @@ public class MongoConfiguration {
@@ -338,7 +340,9 @@ public class MongoConfiguration {
MongoDB Server generation 3 changed the authentication model when connecting to the DB. Therefore, some of the configuration options available for authentication are no longer valid. You should use the `MongoClient`-specific options for setting credentials through `MongoCredential` to provide authentication data, as shown in the following example:
[source,java]
====
.Java
[source,java,role="primary"]
----
@Configuration
public class ApplicationContextEventTestsAppConfig extends AbstractMongoClientConfiguration {
@ -360,26 +364,61 @@ public class ApplicationContextEventTestsAppConfig extends AbstractMongoClientCo
@@ -360,26 +364,61 @@ public class ApplicationContextEventTestsAppConfig extends AbstractMongoClientCo
}
----
In order to use authentication with XML-based configuration, use the `credential` attribute on the `<mongo-client>` element.
.XML
[source,xml,role="secondary"]
----
<mongo:db-factory dbname="database" />
----
====
NOTE: Username and password credentials used in XML-based configuration must be URL-encoded when these contain reserved characters, such as `:`, `%`, `@`, or `,`.
See https://tools.ietf.org/html/rfc3986#section-2.2[section 2.2 of RFC 3986] for further details.
[[mongo.mongo-db-factory-xml]]
=== Registering a `MongoDatabaseFactory` Instance by Using XML-based Metadata
If you need to configure additional options on the `com.mongodb.client.MongoClient` instance that is used to create a `SimpleMongoClientDbFactory`, you can refer to an existing bean as shown in the following example. To show another common usage pattern, the following listing shows the use of a property placeholder, which lets you parametrize the configuration and the creation of a `MongoTemplate`:
The `mongo` namespace provides a convenient way to create a `SimpleMongoClientDbFactory`, as compared to using the `<beans/>` namespace, as shown in the following example:
public class ApplicationContextEventTestsAppConfig extends AbstractMongoClientConfiguration {
If you need to configure additional options on the `com.mongodb.client.MongoClient` instance that is used to create a `SimpleMongoClientDbFactory`, you can refer to an existing bean by using the `mongo-ref` attribute as shown in the following example. To show another common usage pattern, the following listing shows the use of a property placeholder, which lets you parametrize the configuration and the creation of a `MongoTemplate`:
@ -399,6 +438,7 @@ If you need to configure additional options on the `com.mongodb.client.MongoClie
@@ -399,6 +438,7 @@ If you need to configure additional options on the `com.mongodb.client.MongoClie
@ -424,35 +464,30 @@ The next section contains an example of how to work with the `MongoTemplate` in
@@ -424,35 +464,30 @@ The next section contains an example of how to work with the `MongoTemplate` in
[[mongo-template.instantiating]]
=== Instantiating `MongoTemplate`
You can use Java to create and register an instance of `MongoTemplate`, as the following example shows:
You can use the following configuration to create and register an instance of `MongoTemplate`, as the following example shows:
.Registering a `com.mongodb.client.MongoClient` object and enabling Spring's exception translation support
return new MongoTemplate(mongoClient, "geospatial");
}
}
----
====
There are several overloaded constructors of `MongoTemplate`:
* `MongoTemplate(MongoClient mongo, String databaseName)`: Takes the `MongoClient` object and the default database name to operate against.
* `MongoTemplate(MongoDatabaseFactory mongoDbFactory)`: Takes a MongoDbFactory object that encapsulated the `MongoClient` object, database name, and username and password.
* `MongoTemplate(MongoDatabaseFactory mongoDbFactory, MongoConverter mongoConverter)`: Adds a `MongoConverter` to use for mapping.
You can also configure a MongoTemplate by using Spring's XML <beans/> schema, as the following example shows:
@ -461,6 +496,14 @@ You can also configure a MongoTemplate by using Spring's XML <beans/> schema, as
@@ -461,6 +496,14 @@ You can also configure a MongoTemplate by using Spring's XML <beans/> schema, as
There are several overloaded constructors of `MongoTemplate`:
* `MongoTemplate(MongoClient mongo, String databaseName)`: Takes the `MongoClient` object and the default database name to operate against.
* `MongoTemplate(MongoDatabaseFactory mongoDbFactory)`: Takes a MongoDbFactory object that encapsulated the `MongoClient` object, database name, and username and password.
* `MongoTemplate(MongoDatabaseFactory mongoDbFactory, MongoConverter mongoConverter)`: Adds a `MongoConverter` to use for mapping.
Other optional properties that you might like to set when creating a `MongoTemplate` are the default `WriteResultCheckingPolicy`, `WriteConcern`, and `ReadPreference` properties.
@ -677,13 +720,13 @@ To achieve that, the `MappingMongoConverter` uses a `MongoTypeMapper` abstractio
@@ -677,13 +720,13 @@ To achieve that, the `MappingMongoConverter` uses a `MongoTypeMapper` abstractio
====
[source,java]
----
public class Sample {
class Sample {
Contact value;
}
public abstract class Contact { … }
abstract class Contact { … }
public class Person extends Contact { … }
class Person extends Contact { … }
Sample sample = new Sample();
sample.value = new Person();
@ -725,7 +768,7 @@ By default, the configuration class scans the base package for potential candida
@@ -725,7 +768,7 @@ By default, the configuration class scans the base package for potential candida
[source,java]
----
@Configuration
public class AppConfig extends AbstractMongoClientConfiguration {
class AppConfig extends AbstractMongoClientConfiguration {
@Override
protected Set<Class<?>> getInitialEntitySet() {
@ -741,8 +784,6 @@ public class AppConfig extends AbstractMongoClientConfiguration {
@@ -741,8 +784,6 @@ public class AppConfig extends AbstractMongoClientConfiguration {
The following example shows how to configure a custom `MongoTypeMapper` in `MappingMongoConverter`:
.Configuring a custom `MongoTypeMapper` with Spring Java Config
====
[source,java]
----
class CustomMongoTypeMapper extends DefaultMongoTypeMapper {
@ -750,8 +791,10 @@ class CustomMongoTypeMapper extends DefaultMongoTypeMapper {
@@ -750,8 +791,10 @@ class CustomMongoTypeMapper extends DefaultMongoTypeMapper {
}
----
[source,java]
.Configuring a custom `MongoTypeMapper`
====
.Java
[source,java,role="primary"]
----
@Configuration
class SampleMongoConfiguration extends AbstractMongoClientConfiguration {
@ -763,7 +806,8 @@ class SampleMongoConfiguration extends AbstractMongoClientConfiguration {
@@ -763,7 +806,8 @@ class SampleMongoConfiguration extends AbstractMongoClientConfiguration {
@Bean
@Override
public MappingMongoConverter mappingMongoConverter() throws Exception {
public MappingMongoConverter mappingMongoConverter(MongoDatabaseFactory databaseFactory,
@ -775,22 +819,19 @@ class SampleMongoConfiguration extends AbstractMongoClientConfiguration {
@@ -775,22 +819,19 @@ class SampleMongoConfiguration extends AbstractMongoClientConfiguration {
}
}
----
====
Note that the preceding example extends the `AbstractMongoClientConfiguration` class and overrides the bean definition of the `MappingMongoConverter` where we configured our custom `MongoTypeMapper`.
The following example shows how to use XML to configure a custom `MongoTypeMapper`:
Note that the preceding example extends the `AbstractMongoClientConfiguration` class and overrides the bean definition of the `MappingMongoConverter` where we configured our custom `MongoTypeMapper`.
@ -110,7 +110,9 @@ Because our domain repository extends `ReactiveSortingRepository`, it provides y
@@ -110,7 +110,9 @@ Because our domain repository extends `ReactiveSortingRepository`, it provides y
====
[source,java]
----
public class PersonRepositoryTests {
@ExtendWith(SpringExtension.class)
@ContextConfiguration
class PersonRepositoryTests {
@Autowired ReactivePersonRepository repository;
@ -162,7 +164,7 @@ The following example shows how to define a `near` query that finds all persons
@@ -162,7 +164,7 @@ The following example shows how to define a `near` query that finds all persons
====
[source,java]
----
public interface PersonRepository extends ReactiveMongoRepository<Person, String> {
@ -197,7 +199,7 @@ Spring Data MongoDB supports geo-near queries, as the following example shows:
@@ -197,7 +199,7 @@ Spring Data MongoDB supports geo-near queries, as the following example shows:
[source,java]
----
public interface PersonRepository extends ReactiveMongoRepository<Person, String> {
@ -253,7 +255,7 @@ You can use the generated `Predicate` class by using the `ReactiveQuerydslPredic
@@ -253,7 +255,7 @@ You can use the generated `Predicate` class by using the `ReactiveQuerydslPredic
====
[source,java]
----
public interface ReactiveQuerydslPredicateExecutor<T> {
interface ReactiveQuerydslPredicateExecutor<T> {
Mono<T> findOne(Predicate predicate);
@ -278,7 +280,7 @@ To use this in your repository implementation, add it to the list of repository
@@ -278,7 +280,7 @@ To use this in your repository implementation, add it to the list of repository
====
[source,java]
----
public interface PersonRepository extends ReactiveMongoRepository<Person, String>, ReactiveQuerydslPredicateExecutor<Person> {
@ -166,21 +166,14 @@ Please refer to <<mapping.index-creation>> on how to create indexes programmatic
@@ -166,21 +166,14 @@ Please refer to <<mapping.index-creation>> on how to create indexes programmatic
public class Config extends AbstractMongoClientConfiguration {
@Override
protected boolean autoIndexCreation() { <2>
protected boolean autoIndexCreation() {
return true;
}
@ -188,22 +181,25 @@ public class Config extends AbstractMongoClientConfiguration {
@@ -188,22 +181,25 @@ public class Config extends AbstractMongoClientConfiguration {