diff --git a/src/main/asciidoc/reference/mongo-repositories.adoc b/src/main/asciidoc/reference/mongo-repositories.adoc index 4d69ee95dc..67dc4bc564 100644 --- a/src/main/asciidoc/reference/mongo-repositories.adoc +++ b/src/main/asciidoc/reference/mongo-repositories.adoc @@ -4,12 +4,15 @@ [[mongo-repo-intro]] == Introduction -This chapter points out the specialties for repository support for MongoDB. This chapter builds on the core repository support explained in <>. You should have a sound understanding of the basic concepts explained there. +This chapter points out the specialties for repository support for MongoDB. +This chapter builds on the core repository support explained in <>. +You should have a sound understanding of the basic concepts explained there. [[mongo-repo-usage]] == Usage -To access domain entities stored in a MongoDB, you can use our sophisticated repository support that eases implementation quite significantly.To do so, create an interface for your repository, as the following example shows: +To access domain entities stored in a MongoDB, you can use our sophisticated repository support that eases implementation quite significantly. +To do so, create an interface for your repository, as the following example shows: .Sample Person entity ==== @@ -28,7 +31,8 @@ public class Person { ---- ==== -Note that the domain type shown in the preceding example has a property named `id` of type `String`.The default serialization mechanism used in `MongoTemplate` (which backs the repository support) regards properties named `id` as the document ID. Currently, we support `String`, `ObjectId`, and `BigInteger` as ID types. +Note that the domain type shown in the preceding example has a property named `id` of type `String`.The default serialization mechanism used in `MongoTemplate` (which backs the repository support) regards properties named `id` as the document ID. +Currently, we support `String`, `ObjectId`, and `BigInteger` as ID types. Please see <> for more information about on how the `id` field is handled in the mapping layer. Now that we have a domain object, we can define an interface that uses it, as follows: @@ -44,12 +48,12 @@ public interface PersonRepository extends PagingAndSortingRepository findAllBy(); <5> } ---- -<1> The `findByLastname` method shows a query for all people with the given last name. The query is derived by parsing the method name for constraints that can be concatenated with `And` and `Or`. Thus, the method name results in a query expression of `{"lastname" : lastname}`. -<2> Applies pagination to a query. You can equip your method signature with a `Pageable` parameter and let the method return a `Page` instance and Spring Data automatically pages the query accordingly. -<3> Shows that you can query based on properties that are not primitive types. Throws `IncorrectResultSizeDataAccessException` if more than one match is found. -<4> Uses the `First` keyword to restrict the query to only the first result. Unlike <3>, this method does not throw an exception if more than one match is found. + +<1> The `findByLastname` method shows a query for all people with the given last name. +The query is derived by parsing the method name for constraints that can be concatenated with `And` and `Or`. +Thus, the method name results in a query expression of `{"lastname" : lastname}`. +<2> Applies pagination to a query. +You can equip your method signature with a `Pageable` parameter and let the method return a `Page` instance and Spring Data automatically pages the query accordingly. +<3> Shows that you can query based on properties that are not primitive types. +Throws `IncorrectResultSizeDataAccessException` if more than one match is found. +<4> Uses the `First` keyword to restrict the query to only the first result. +Unlike <3>, this method does not throw an exception if more than one match is found. <5> Uses a Java 8 `Stream` that reads and converts individual elements while iterating the stream. ==== @@ -161,7 +175,7 @@ NOTE: We do not support referring to parameters that are mapped as `DBRef` in th The following table shows the keywords that are supported for query methods: -[cols="1,2,3", options="header"] +[cols="1,2,3",options="header"] .Supported keywords for query methods |=== | Keyword @@ -310,6 +324,7 @@ public interface PersonRepository extends MongoRepository { Optional deleteByBirthdate(Date birthdate); <4> } ---- + <1> Using a return type of `List` retrieves and returns all matching documents before actually deleting them. <2> A numeric return type directly removes the matching documents, returning the total number of documents removed. <3> A single domain type result retrieves and removes the first matching document. @@ -319,7 +334,8 @@ public interface PersonRepository extends MongoRepository { [[mongodb.repositories.queries.geo-spatial]] === Geo-spatial Repository Queries -As you saw in the preceding table of keywords, a few keywords trigger geo-spatial operations within a MongoDB query. The `Near` keyword allows some further modification, as the next few examples show. +As you saw in the preceding table of keywords, a few keywords trigger geo-spatial operations within a MongoDB query. +The `Near` keyword allows some further modification, as the next few examples show. The following example shows how to define a `near` query that finds all persons with a given distance of a given point: @@ -335,7 +351,8 @@ public interface PersonRepository extends MongoRepository { ---- ==== -Adding a `Distance` parameter to the query method allows restricting results to those within the given distance. If the `Distance` was set up containing a `Metric`, we transparently use `$nearSphere` instead of `$code`, as the following example shows: +Adding a `Distance` parameter to the query method allows restricting results to those within the given distance. +If the `Distance` was set up containing a `Metric`, we transparently use `$nearSphere` instead of `$code`, as the following example shows: .Using `Distance` with `Metrics` ==== @@ -348,9 +365,12 @@ Distance distance = new Distance(200, Metrics.KILOMETERS); ---- ==== -Using a `Distance` with a `Metric` causes a `$nearSphere` (instead of a plain `$near`) clause to be added. Beyond that, the actual distance gets calculated according to the `Metrics` used. +Using a `Distance` with a `Metric` causes a `$nearSphere` (instead of a plain `$near`) clause to be added. +Beyond that, the actual distance gets calculated according to the `Metrics` used. -(Note that `Metric` does not refer to metric units of measure. It could be miles rather than kilometers. Rather, `metric` refers to the concept of a system of measurement, regardless of which system you use.) +(Note that `Metric` does not refer to metric units of measure. +It could be miles rather than kilometers. +Rather, `metric` refers to the concept of a system of measurement, regardless of which system you use.) NOTE: Using `@GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)` on the target property forces usage of the `$nearSphere` operator. @@ -411,12 +431,14 @@ public interface PersonRepository extends MongoRepository { } ---- -The query in the preceding example returns only the `firstname`, `lastname` and `Id` properties of the `Person` objects. The `age` property, a `java.lang.Integer`, is not set and its value is therefore null. +The query in the preceding example returns only the `firstname`, `lastname` and `Id` properties of the `Person` objects. +The `age` property, a `java.lang.Integer`, is not set and its value is therefore null. [[mongodb.repositories.queries.sort]] === Sorting Query Method results -MongoDB repositories allow various approaches to define sorting order. Let's take a look at the following example: +MongoDB repositories allow various approaches to define sorting order. +Let's take a look at the following example: .Sorting Query Results ==== @@ -435,11 +457,16 @@ public interface PersonRepository extends MongoRepository { List findByLastname(String lastname, Sort sort); <4> } ---- + <1> Static sorting derived from method name. `SortByAgeDesc` results in `{ age : -1 }` for the sort parameter. -<2> Dynamic sorting using a method argument. `Sort.by(DESC, "age")` creates `{ age : -1 }` for the sort parameter. -<3> Static sorting via `Query` annotation. Sort parameter applied as stated in the `sort` attribute. +<2> Dynamic sorting using a method argument. +`Sort.by(DESC, "age")` creates `{ age : -1 }` for the sort parameter. +<3> Static sorting via `Query` annotation. +Sort parameter applied as stated in the `sort` attribute. <4> Default sorting via `Query` annotation combined with dynamic one via a method argument. `Sort.unsorted()` -results in `{ age : -1 }`. Using `Sort.by(ASC, "age")` overrides the defaults and creates `{ age : 1 }`. `Sort.by +results in `{ age : -1 }`. +Using `Sort.by(ASC, "age")` overrides the defaults and creates `{ age : 1 }`. +`Sort.by (ASC, "firstname")` alters the default and results in `{ age : -1, firstname : 1 }`. ==== @@ -449,7 +476,8 @@ results in `{ age : -1 }`. Using `Sort.by(ASC, "age")` overrides the defaults an Query strings and field definitions can be used together with SpEL expressions to create dynamic queries at runtime. SpEL expressions can provide predicate values and can be used to extend predicates with subdocuments. -Expressions expose method arguments through an array that contains all the arguments.The following query uses `[0]` +Expressions expose method arguments through an array that contains all the arguments. +The following query uses `[0]` to declare the predicate value for `lastname` (which is equivalent to the `?0` parameter binding): [source,java] @@ -461,8 +489,8 @@ public interface PersonRepository extends MongoRepository { } ---- -Expressions can be used to invoke functions, evaluate conditionals, and construct values.SpEL expressions -used in conjunction with JSON reveal a side-effect, because Map-like declarations inside of SpEL read like JSON, as the following example shows: +Expressions can be used to invoke functions, evaluate conditionals, and construct values. +SpEL expressions used in conjunction with JSON reveal a side-effect, because Map-like declarations inside of SpEL read like JSON, as the following example shows: [source,java] ---- @@ -473,12 +501,14 @@ public interface PersonRepository extends MongoRepository { } ---- -SpEL in query strings can be a powerful way to enhance queries.However, they can also accept a broad range of unwanted arguments. +SpEL in query strings can be a powerful way to enhance queries. +However, they can also accept a broad range of unwanted arguments. You should make sure to sanitize strings before passing them to the query to avoid unwanted changes to your query. Expression support is extensible through the Query SPI: `org.springframework.data.repository.query.spi.EvaluationContextExtension`. -The Query SPI can contribute properties and functions and can customize the root object.Extensions are retrieved from the application context -at the time of SpEL evaluation when the query is built.The following example shows how to use `EvaluationContextExtension`: +The Query SPI can contribute properties and functions and can customize the root object. +Extensions are retrieved from the application context at the time of SpEL evaluation when the query is built. +The following example shows how to use `EvaluationContextExtension`: [source,java] ---- @@ -525,7 +555,9 @@ Page page = repository.findAll(person.lastname.contains("a"), PageRequest.of(0, 2, Direction.ASC, "lastname")); ---- -`QPerson` is a class that is generated by the Java annotation post-processing tool.It is a `Predicate` that lets you write type-safe queries.Notice that there are no strings in the query other than the `C0123` value. +`QPerson` is a class that is generated by the Java annotation post-processing tool. +It is a `Predicate` that lets you write type-safe queries. +Notice that there are no strings in the query other than the `C0123` value. You can use the generated `Predicate` class by using the `QuerydslPredicateExecutor` interface, which the following listing shows: @@ -558,11 +590,16 @@ public interface PersonRepository extends MongoRepository, Query [[mongodb.repositories.queries.full-text]] === Full-text Search Queries -MongoDB's full-text search feature is store-specific and, therefore, can be found on `MongoRepository` rather than on the more general `CrudRepository`. We need a document with a full-text index (see "`<>`" to learn how to create a full-text index). +MongoDB's full-text search feature is store-specific and, therefore, can be found on `MongoRepository` rather than on the more general `CrudRepository`. +We need a document with a full-text index (see "`<>`" to learn how to create a full-text index). -Additional methods on `MongoRepository` take `TextCriteria` as an input parameter. In addition to those explicit methods, it is also possible to add a `TextCriteria`-derived repository method. The criteria are added as an additional `AND` criteria. Once the entity contains a `@TextScore`-annotated property, the document's full-text score can be retrieved. Furthermore, the `@TextScore` annotated also makes it possible to sort by the document's score, as the following example shows: +Additional methods on `MongoRepository` take `TextCriteria` as an input parameter. +In addition to those explicit methods, it is also possible to add a `TextCriteria`-derived repository method. +The criteria are added as an additional `AND` criteria. +Once the entity contains a `@TextScore`-annotated property, the document's full-text score can be retrieved. +Furthermore, the `@TextScore` annotated also makes it possible to sort by the document's score, as the following example shows: -[source, java] +[source,java] ---- @Document class FullTextDocument { @@ -602,7 +639,11 @@ include::./mongo-repositories-aggregation.adoc[] [[mongodb.repositories.misc.cdi-integration]] == CDI Integration -Instances of the repository interfaces are usually created by a container, and Spring is the most natural choice when working with Spring Data. As of version 1.3.0, Spring Data MongoDB ships with a custom CDI extension that lets you use the repository abstraction in CDI environments. The extension is part of the JAR. To activate it, drop the Spring Data MongoDB JAR into your classpath. You can now set up the infrastructure by implementing a CDI Producer for the `MongoTemplate`, as the following example shows: +Instances of the repository interfaces are usually created by a container, and Spring is the most natural choice when working with Spring Data. +As of version 1.3.0, Spring Data MongoDB ships with a custom CDI extension that lets you use the repository abstraction in CDI environments. +The extension is part of the JAR. +To activate it, drop the Spring Data MongoDB JAR into your classpath. +You can now set up the infrastructure by implementing a CDI Producer for the `MongoTemplate`, as the following example shows: [source,java] ---- @@ -618,7 +659,8 @@ class MongoTemplateProducer { } ---- -The Spring Data MongoDB CDI extension picks up the `MongoTemplate` available as a CDI bean and creates a proxy for a Spring Data repository whenever a bean of a repository type is requested by the container. Thus, obtaining an instance of a Spring Data repository is a matter of declaring an `@Inject`-ed property, as the following example shows: +The Spring Data MongoDB CDI extension picks up the `MongoTemplate` available as a CDI bean and creates a proxy for a Spring Data repository whenever a bean of a repository type is requested by the container. +Thus, obtaining an instance of a Spring Data repository is a matter of declaring an `@Inject`-ed property, as the following example shows: [source,java] ----