Browse Source

template configuration, done. next: -> template crud operations

labs/antora
Christoph Strobl 2 years ago
parent
commit
f052ae1794
No known key found for this signature in database
GPG Key ID: 8CC1AB53391458C8
  1. 3
      src/main/antora/modules/ROOT/nav.adoc
  2. 108
      src/main/antora/modules/ROOT/pages/mongodb/mongo-template.adoc
  3. 34
      src/main/antora/modules/ROOT/pages/mongodb/template-api.adoc
  4. 145
      src/main/antora/modules/ROOT/pages/mongodb/template-config.adoc

3
src/main/antora/modules/ROOT/nav.adoc

@ -7,7 +7,8 @@ @@ -7,7 +7,8 @@
* xref:mongodb.adoc[]
** xref:mongodb/getting-started.adoc[]
** xref:mongodb/configuration.adoc[]
*** xref:mongodb/mongo-template.adoc[]
** xref:mongodb/template-api.adoc[]
*** xref:mongodb/template-config.adoc[]
*** xref:mongodb/mongo-template-save-update-remove.adoc[]
*** xref:mongodb/mongo-query.adoc[]
**** xref:mongodb/mongo-query/template.adoc[]

108
src/main/antora/modules/ROOT/pages/mongodb/mongo-template.adoc

@ -1,108 +0,0 @@ @@ -1,108 +0,0 @@
[[mongo-template]]
= Introduction to `MongoTemplate`
The `MongoTemplate` class, located in the `org.springframework.data.mongodb.core` package, is the central class of Spring's MongoDB support and provides a rich feature set for interacting with the database. The template offers convenience operations to create, update, delete, and query MongoDB documents and provides a mapping between your domain objects and MongoDB documents.
NOTE: Once configured, `MongoTemplate` is thread-safe and can be reused across multiple instances.
The mapping between MongoDB documents and domain classes is done by delegating to an implementation of the `MongoConverter` interface. Spring provides `MappingMongoConverter`, but you can also write your own converter. See "`xref:reference/mongo-custom-conversions.adoc[Custom Conversions - Overriding Default Mapping]`" for more detailed information.
The `MongoTemplate` class implements the interface `MongoOperations`. In as much as possible, the methods on `MongoOperations` are named after methods available on the MongoDB driver `Collection` object, to make the API familiar to existing MongoDB developers who are used to the driver API. For example, you can find methods such as `find`, `findAndModify`, `findAndReplace`, `findOne`, `insert`, `remove`, `save`, `update`, and `updateMulti`. The design goal was to make it as easy as possible to transition between the use of the base MongoDB driver and `MongoOperations`. A major difference between the two APIs is that `MongoOperations` can be passed domain objects instead of `Document`. Also, `MongoOperations` has fluent APIs for `Query`, `Criteria`, and `Update` operations instead of populating a `Document` to specify the parameters for those operations.
NOTE: The preferred way to reference the operations on `MongoTemplate` instance is through its interface, `MongoOperations`.
The default converter implementation used by `MongoTemplate` is `MappingMongoConverter`. While the `MappingMongoConverter` can use additional metadata to specify the mapping of objects to documents, it can also convert objects that contain no additional metadata by using some conventions for the mapping of IDs and collection names. These conventions, as well as the use of mapping annotations, are explained in the "`xref:reference/mapping.adoc[Mapping]`" chapter.
Another central feature of `MongoTemplate` is translation of exceptions thrown by the MongoDB Java driver into Spring's portable Data Access Exception hierarchy. See "`xref:reference/mongodb/mongo-exception.adoc[Exception Translation]`" for more information.
`MongoTemplate` offers many convenience methods to help you easily perform common tasks. However, if you need to directly access the MongoDB driver API, you can use one of several `Execute` callback methods. The `execute` callbacks gives you a reference to either a `com.mongodb.client.MongoCollection` or a `com.mongodb.client.MongoDatabase` object. See the xref:reference/mongodb/mongo-executioncallback.adoc["`Execution Callbacks`"] section for more information.
The next section contains an example of how to work with the `MongoTemplate` in the context of the Spring container.
[[mongo-template.instantiating]]
== Instantiating `MongoTemplate`
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
====
.Java
[source,java,role="primary"]
----
@Configuration
class AppConfig {
@Bean
MongoClient mongoClient() {
return MongoClients.create("mongodb://localhost:27017");
}
@Bean
MongoTemplate mongoTemplate(MongoClient mongoClient) {
return new MongoTemplate(mongoClient, "geospatial");
}
}
----
.XML
[source,xml,role="secondary"]
----
<mongo:mongo-client host="localhost" port="27017"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoClient"/>
<constructor-arg name="databaseName" value="geospatial"/>
</bean>
----
====
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.
NOTE: The preferred way to reference the operations on `MongoTemplate` instance is through its interface, `MongoOperations`.
[[mongo-template.writeresultchecking]]
== `WriteResultChecking` Policy
When in development, it is handy to either log or throw an exception if the `com.mongodb.WriteResult` returned from any MongoDB operation contains an error. It is quite common to forget to do this during development and then end up with an application that looks like it runs successfully when, in fact, the database was not modified according to your expectations. You can set the `WriteResultChecking` property of `MongoTemplate` to one of the following values: `EXCEPTION` or `NONE`, to either throw an `Exception` or do nothing, respectively. The default is to use a `WriteResultChecking` value of `NONE`.
[[mongo-template.writeconcern]]
== `WriteConcern`
If it has not yet been specified through the driver at a higher level (such as `com.mongodb.client.MongoClient`), you can set the `com.mongodb.WriteConcern` property that the `MongoTemplate` uses for write operations. If the `WriteConcern` property is not set, it defaults to the one set in the MongoDB driver's DB or Collection setting.
[[mongo-template.writeconcernresolver]]
== `WriteConcernResolver`
For more advanced cases where you want to set different `WriteConcern` values on a per-operation basis (for remove, update, insert, and save operations), a strategy interface called `WriteConcernResolver` can be configured on `MongoTemplate`. Since `MongoTemplate` is used to persist POJOs, the `WriteConcernResolver` lets you create a policy that can map a specific POJO class to a `WriteConcern` value. The following listing shows the `WriteConcernResolver` interface:
[source,java]
----
public interface WriteConcernResolver {
WriteConcern resolve(MongoAction action);
}
----
You can use the `MongoAction` argument to determine the `WriteConcern` value or use the value of the Template itself as a default. `MongoAction` contains the collection name being written to, the `java.lang.Class` of the POJO, the converted `Document`, the operation (`REMOVE`, `UPDATE`, `INSERT`, `INSERT_LIST`, or `SAVE`), and a few other pieces of contextual information. The following example shows two sets of classes getting different `WriteConcern` settings:
[source]
----
private class MyAppWriteConcernResolver implements WriteConcernResolver {
public WriteConcern resolve(MongoAction action) {
if (action.getEntityClass().getSimpleName().contains("Audit")) {
return WriteConcern.NONE;
} else if (action.getEntityClass().getSimpleName().contains("Metadata")) {
return WriteConcern.JOURNAL_SAFE;
}
return action.getDefaultWriteConcern();
}
}
----

34
src/main/antora/modules/ROOT/pages/mongodb/template-api.adoc

@ -0,0 +1,34 @@ @@ -0,0 +1,34 @@
[[mongo-template]]
= Introduction to `MongoTemplate`
The `MongoTemplate` and its reactive counterpart class, located in the `org.springframework.data.mongodb.core` package, is the central class of Spring's MongoDB support and provides a rich feature set for interacting with the database.
The template offers convenience operations to create, update, delete, and query MongoDB documents and provides a mapping between your domain objects and MongoDB documents.
NOTE: Once configured, `MongoTemplate` is thread-safe and can be reused across multiple instances.
The mapping between MongoDB documents and domain classes is done by delegating to an implementation of the `MongoConverter` interface.
Spring provides `MappingMongoConverter`, but you can also write your own converter.
See "`xref:reference/mongo-custom-conversions.adoc[Custom Conversions - Overriding Default Mapping]`" for more detailed information.
The `MongoTemplate` class implements the interface `MongoOperations`.
In as much as possible, the methods on `MongoOperations` are named after methods available on the MongoDB driver `Collection` object, to make the API familiar to existing MongoDB developers who are used to the driver API.
For example, you can find methods such as `find`, `findAndModify`, `findAndReplace`, `findOne`, `insert`, `remove`, `save`, `update`, and `updateMulti`.
The design goal was to make it as easy as possible to transition between the use of the base MongoDB driver and `MongoOperations`.
A major difference between the two APIs is that `MongoOperations` can be passed domain objects instead of `Document`.
Also, `MongoOperations` has fluent APIs for `Query`, `Criteria`, and `Update` operations instead of populating a `Document` to specify the parameters for those operations.
NOTE: The preferred way to reference the operations on `MongoTemplate` instance is through its interface, `MongoOperations`.
The default converter implementation used by `MongoTemplate` is `MappingMongoConverter`.
While the `MappingMongoConverter` can use additional metadata to specify the mapping of objects to documents, it can also convert objects that contain no additional metadata by using some conventions for the mapping of IDs and collection names.
These conventions, as well as the use of mapping annotations, are explained in the "`xref:reference/mapping.adoc[Mapping]`" chapter.
Another central feature of `MongoTemplate` is translation of exceptions thrown by the MongoDB Java driver into Spring's portable Data Access Exception hierarchy.
See "`xref:reference/mongodb/mongo-exception.adoc[Exception Translation]`" for more information.
`MongoTemplate` offers many convenience methods to help you easily perform common tasks.
However, if you need to directly access the MongoDB driver API, you can use one of several `Execute` callback methods.
The `execute` callbacks gives you a reference to either a `MongoCollection` or a `MongoDatabase` object.
See the xref:reference/mongodb/mongo-executioncallback.adoc["`Execution Callbacks`"] section for more information.
The next section contains an example of how to work with the `MongoTemplate` in the context of the Spring container.

145
src/main/antora/modules/ROOT/pages/mongodb/template-config.adoc

@ -0,0 +1,145 @@ @@ -0,0 +1,145 @@
[[mongo-template.instantiating]]
== `MongoTemplate` Configuration
You can use the following configuration to create and register an instance of `MongoTemplate`, as the following example shows:
.Registering a `MongoClient` object and enabling Spring's exception translation support
[tabs]
======
Imperative::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
@Configuration
class ApplicationConfiguration {
@Bean
MongoClient mongoClient() {
return MongoClients.create("mongodb://localhost:27017");
}
@Bean
MongoOperations mongoTemplate(MongoClient mongoClient) {
return new MongoTemplate(mongoClient, "geospatial");
}
}
----
Reactive::
+
[source,java,indent=0,subs="verbatim,quotes",role="secondary"]
----
@Configuration
class ReactiveApplicationConfiguration {
@Bean
MongoClient mongoClient() {
return MongoClients.create("mongodb://localhost:27017");
}
@Bean
ReactiveMongoOperations mongoTemplate(MongoClient mongoClient) {
return new ReactiveMongoTemplate(mongoClient, "geospatial");
}
}
----
XML::
+
[source,xml,indent=0,subs="verbatim,quotes",role="third"]
----
<mongo:mongo-client host="localhost" port="27017"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoClient"/>
<constructor-arg name="databaseName" value="geospatial"/>
</bean>
----
======
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` / `ReactiveMongoTemplate` are the default `WriteResultCheckingPolicy`, `WriteConcern`, and `ReadPreference` properties.
[[mongo-template.writeresultchecking]]
== `WriteResultChecking` Policy
When in development, it is handy to either log or throw an exception if the `com.mongodb.WriteResult` returned from any MongoDB operation contains an error. It is quite common to forget to do this during development and then end up with an application that looks like it runs successfully when, in fact, the database was not modified according to your expectations. You can set the `WriteResultChecking` property of `MongoTemplate` to one of the following values: `EXCEPTION` or `NONE`, to either throw an `Exception` or do nothing, respectively. The default is to use a `WriteResultChecking` value of `NONE`.
[[mongo-template.writeconcern]]
== `WriteConcern`
If it has not yet been specified through the driver at a higher level (such as `com.mongodb.client.MongoClient`), you can set the `com.mongodb.WriteConcern` property that the `MongoTemplate` uses for write operations. If the `WriteConcern` property is not set, it defaults to the one set in the MongoDB driver's DB or Collection setting.
[[mongo-template.writeconcernresolver]]
== `WriteConcernResolver`
For more advanced cases where you want to set different `WriteConcern` values on a per-operation basis (for remove, update, insert, and save operations), a strategy interface called `WriteConcernResolver` can be configured on `MongoTemplate`. Since `MongoTemplate` is used to persist POJOs, the `WriteConcernResolver` lets you create a policy that can map a specific POJO class to a `WriteConcern` value. The following listing shows the `WriteConcernResolver` interface:
[source,java]
----
public interface WriteConcernResolver {
WriteConcern resolve(MongoAction action);
}
----
You can use the `MongoAction` argument to determine the `WriteConcern` value or use the value of the Template itself as a default.
`MongoAction` contains the collection name being written to, the `java.lang.Class` of the POJO, the converted `Document`, the operation (`REMOVE`, `UPDATE`, `INSERT`, `INSERT_LIST`, or `SAVE`), and a few other pieces of contextual information.
The following example shows two sets of classes getting different `WriteConcern` settings:
[source]
----
private class MyAppWriteConcernResolver implements WriteConcernResolver {
@Override
public WriteConcern resolve(MongoAction action) {
if (action.getEntityType().getSimpleName().contains("Audit")) {
return WriteConcern.ACKNOWLEDGED;
} else if (action.getEntityType().getSimpleName().contains("Metadata")) {
return WriteConcern.JOURNALED;
}
return action.getDefaultWriteConcern();
}
}
----
[[mongo-template.entity-lifecycle-events]]
== Publish entity lifecycle events
The template publishes xref:mongodb/mapping-usage-events.adoc#mongodb.mapping-usage.events[lifecycle events].
In case there are no listeners present, this feature can be disabled.
[source,java]
----
@Bean
MongoOperations mongoTemplate(MongoClient mongoClient) {
MongoTemplate template = new MongoTemplate(mongoClient, "geospatial");
template.setEntityLifecycleEventsEnabled(false);
// ...
}
----
[[mongo-template.entity-callbacks-config]]
== Configure `EntityCallbacks`
Nest to lifecycle events the template invokes xref:mongodb/mongo-entity-callbacks.adoc[EntityCallbacks] which can be (if not auto configured) set via the template API.
[source,java]
----
@Bean
MongoOperations mongoTemplate(MongoClient mongoClient) {
MongoTemplate template = new MongoTemplate(mongoClient, "geospatial");
template.setEntityCallbacks(EntityCallbacks.create(...));
// ...
}
----
[[mongo-template.count-documents-config]]
== Documents count configuration
By setting `MongoTemplate#useEstimatedCount(...)` to `true` _MongoTemplate#count(...)_ operations, that use an empty filter query, will be delegated to `estimatedCount`, as long as there is no transaction active and the template is not bound to a xref:mongodb/client-session-transactions.adoc[session].
Please refer to to the xref:mongodb/mongo-query-count.adoc#mongo.query.count[Counting Documents] section for more information.
Loading…
Cancel
Save