Skip to content

Commit ebc4678

Browse files
committed
Polishing.
Reformat asciidoc source. See #4085
1 parent 28d6e67 commit ebc4678

File tree

1 file changed

+80
-38
lines changed

1 file changed

+80
-38
lines changed

src/main/asciidoc/reference/mongo-repositories.adoc

+80-38
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,15 @@
44
[[mongo-repo-intro]]
55
== Introduction
66

7-
This chapter points out the specialties for repository support for MongoDB. This chapter builds on the core repository support explained in <<repositories>>. You should have a sound understanding of the basic concepts explained there.
7+
This chapter points out the specialties for repository support for MongoDB.
8+
This chapter builds on the core repository support explained in <<repositories>>.
9+
You should have a sound understanding of the basic concepts explained there.
810

911
[[mongo-repo-usage]]
1012
== Usage
1113

12-
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:
14+
To access domain entities stored in a MongoDB, you can use our sophisticated repository support that eases implementation quite significantly.
15+
To do so, create an interface for your repository, as the following example shows:
1316

1417
.Sample Person entity
1518
====
@@ -28,7 +31,8 @@ public class Person {
2831
----
2932
====
3033

31-
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.
34+
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.
35+
Currently, we support `String`, `ObjectId`, and `BigInteger` as ID types.
3236
Please see <<mongo-template.id-handling, ID mapping>> for more information about on how the `id` field is handled in the mapping layer.
3337

3438
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<Person, Str
4448
----
4549
====
4650

47-
48-
4951
Right now this interface serves only to provide type information, but we can add additional methods to it later.
5052

5153
To start using the repository, use the `@EnableMongoRepositories` annotation.
52-
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:
54+
That annotation carries the same attributes as the namespace element.
55+
If no base package is configured, the infrastructure scans the package of the annotated configuration class.
56+
The following example shows how to use Java configuration for a repository:
5357

5458
.Java configuration for repositories
5559
====
@@ -100,11 +104,12 @@ If you would rather go with XML based configuration add the following content:
100104
----
101105
====
102106

103-
This namespace element causes the base packages to be scanned for interfaces that extend `MongoRepository` and create Spring beans for each one found.By default, the repositories get a `MongoTemplate` Spring bean wired that is called `mongoTemplate`, so you only need to configure `mongo-template-ref` explicitly if you deviate from this convention.
104-
105-
107+
This namespace element causes the base packages to be scanned for interfaces that extend `MongoRepository` and create Spring beans for each one found.
108+
By default, the repositories get a `MongoTemplate` Spring bean wired that is called `mongoTemplate`, so you only need to configure `mongo-template-ref` explicitly if you deviate from this convention.
106109

107-
Because our domain repository extends `PagingAndSortingRepository`, it provides you with CRUD operations as well as methods for paginated and sorted access to the entities.Working with the repository instance is just a matter of dependency injecting it into a client.Consequently, accessing the second page of `Person` objects at a page size of 10 would resemble the following code:
110+
Because our domain repository extends `PagingAndSortingRepository`, it provides you with CRUD operations as well as methods for paginated and sorted access to the entities.
111+
Working with the repository instance is just a matter of dependency injecting it into a client .
112+
Consequently, accessing the second page of `Person` objects at a page size of 10 would resemble the following code:
108113

109114
.Paging access to Person entities
110115
====
@@ -126,12 +131,15 @@ public class PersonRepositoryTests {
126131
----
127132
====
128133

129-
The preceding example creates an application context with Spring's unit test support, which performs annotation-based dependency injection into test cases.Inside the test method, we use the repository to query the datastore.We hand the repository a `PageRequest` instance that requests the first page of `Person` objects at a page size of 10.
134+
The preceding example creates an application context with Spring's unit test support, which performs annotation-based dependency injection into test cases.
135+
Inside the test method, we use the repository to query the datastore.
136+
We hand the repository a `PageRequest` instance that requests the first page of `Person` objects at a page size of 10.
130137

131138
[[mongodb.repositories.queries]]
132139
== Query Methods
133140

134-
Most of the data access operations you usually trigger on a repository result in a query being executed against the MongoDB databases.Defining such a query is a matter of declaring a method on the repository interface, as the following example shows:
141+
Most of the data access operations you usually trigger on a repository result in a query being executed against the MongoDB databases.
142+
Defining such a query is a matter of declaring a method on the repository interface, as the following example shows:
135143

136144
.PersonRepository with query methods
137145
====
@@ -150,18 +158,24 @@ public interface PersonRepository extends PagingAndSortingRepository<Person, Str
150158
Stream<Person> findAllBy(); <5>
151159
}
152160
----
153-
<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}`.
154-
<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.
155-
<3> Shows that you can query based on properties that are not primitive types. Throws `IncorrectResultSizeDataAccessException` if more than one match is found.
156-
<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.
161+
162+
<1> The `findByLastname` method shows a query for all people with the given last name.
163+
The query is derived by parsing the method name for constraints that can be concatenated with `And` and `Or`.
164+
Thus, the method name results in a query expression of `{"lastname" : lastname}`.
165+
<2> Applies pagination to a query.
166+
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.
167+
<3> Shows that you can query based on properties that are not primitive types.
168+
Throws `IncorrectResultSizeDataAccessException` if more than one match is found.
169+
<4> Uses the `First` keyword to restrict the query to only the first result.
170+
Unlike <3>, this method does not throw an exception if more than one match is found.
157171
<5> Uses a Java 8 `Stream` that reads and converts individual elements while iterating the stream.
158172
====
159173

160174
NOTE: We do not support referring to parameters that are mapped as `DBRef` in the domain class.
161175

162176
The following table shows the keywords that are supported for query methods:
163177

164-
[cols="1,2,3", options="header"]
178+
[cols="1,2,3",options="header"]
165179
.Supported keywords for query methods
166180
|===
167181
| Keyword
@@ -310,6 +324,7 @@ public interface PersonRepository extends MongoRepository<Person, String> {
310324
Optional<Person> deleteByBirthdate(Date birthdate); <4>
311325
}
312326
----
327+
313328
<1> Using a return type of `List` retrieves and returns all matching documents before actually deleting them.
314329
<2> A numeric return type directly removes the matching documents, returning the total number of documents removed.
315330
<3> A single domain type result retrieves and removes the first matching document.
@@ -319,7 +334,8 @@ public interface PersonRepository extends MongoRepository<Person, String> {
319334
[[mongodb.repositories.queries.geo-spatial]]
320335
=== Geo-spatial Repository Queries
321336

322-
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.
337+
As you saw in the preceding table of keywords, a few keywords trigger geo-spatial operations within a MongoDB query.
338+
The `Near` keyword allows some further modification, as the next few examples show.
323339

324340
The following example shows how to define a `near` query that finds all persons with a given distance of a given point:
325341

@@ -335,7 +351,8 @@ public interface PersonRepository extends MongoRepository<Person, String> {
335351
----
336352
====
337353

338-
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:
354+
Adding a `Distance` parameter to the query method allows restricting results to those within the given distance.
355+
If the `Distance` was set up containing a `Metric`, we transparently use `$nearSphere` instead of `$code`, as the following example shows:
339356

340357
.Using `Distance` with `Metrics`
341358
====
@@ -348,9 +365,12 @@ Distance distance = new Distance(200, Metrics.KILOMETERS);
348365
----
349366
====
350367

351-
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.
368+
Using a `Distance` with a `Metric` causes a `$nearSphere` (instead of a plain `$near`) clause to be added.
369+
Beyond that, the actual distance gets calculated according to the `Metrics` used.
352370

353-
(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.)
371+
(Note that `Metric` does not refer to metric units of measure.
372+
It could be miles rather than kilometers.
373+
Rather, `metric` refers to the concept of a system of measurement, regardless of which system you use.)
354374

355375
NOTE: Using `@GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)` on the target property forces usage of the `$nearSphere` operator.
356376

@@ -411,12 +431,14 @@ public interface PersonRepository extends MongoRepository<Person, String> {
411431
}
412432
----
413433

414-
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.
434+
The query in the preceding example returns only the `firstname`, `lastname` and `Id` properties of the `Person` objects.
435+
The `age` property, a `java.lang.Integer`, is not set and its value is therefore null.
415436

416437
[[mongodb.repositories.queries.sort]]
417438
=== Sorting Query Method results
418439

419-
MongoDB repositories allow various approaches to define sorting order. Let's take a look at the following example:
440+
MongoDB repositories allow various approaches to define sorting order.
441+
Let's take a look at the following example:
420442

421443
.Sorting Query Results
422444
====
@@ -435,11 +457,16 @@ public interface PersonRepository extends MongoRepository<Person, String> {
435457
List<Person> findByLastname(String lastname, Sort sort); <4>
436458
}
437459
----
460+
438461
<1> Static sorting derived from method name. `SortByAgeDesc` results in `{ age : -1 }` for the sort parameter.
439-
<2> Dynamic sorting using a method argument. `Sort.by(DESC, "age")` creates `{ age : -1 }` for the sort parameter.
440-
<3> Static sorting via `Query` annotation. Sort parameter applied as stated in the `sort` attribute.
462+
<2> Dynamic sorting using a method argument.
463+
`Sort.by(DESC, "age")` creates `{ age : -1 }` for the sort parameter.
464+
<3> Static sorting via `Query` annotation.
465+
Sort parameter applied as stated in the `sort` attribute.
441466
<4> Default sorting via `Query` annotation combined with dynamic one via a method argument. `Sort.unsorted()`
442-
results in `{ age : -1 }`. Using `Sort.by(ASC, "age")` overrides the defaults and creates `{ age : 1 }`. `Sort.by
467+
results in `{ age : -1 }`.
468+
Using `Sort.by(ASC, "age")` overrides the defaults and creates `{ age : 1 }`.
469+
`Sort.by
443470
(ASC, "firstname")` alters the default and results in `{ age : -1, firstname : 1 }`.
444471
====
445472

@@ -449,7 +476,8 @@ results in `{ age : -1 }`. Using `Sort.by(ASC, "age")` overrides the defaults an
449476
Query strings and field definitions can be used together with SpEL expressions to create dynamic queries at runtime.
450477
SpEL expressions can provide predicate values and can be used to extend predicates with subdocuments.
451478

452-
Expressions expose method arguments through an array that contains all the arguments.The following query uses `[0]`
479+
Expressions expose method arguments through an array that contains all the arguments.
480+
The following query uses `[0]`
453481
to declare the predicate value for `lastname` (which is equivalent to the `?0` parameter binding):
454482

455483
[source,java]
@@ -461,8 +489,8 @@ public interface PersonRepository extends MongoRepository<Person, String> {
461489
}
462490
----
463491

464-
Expressions can be used to invoke functions, evaluate conditionals, and construct values.SpEL expressions
465-
used in conjunction with JSON reveal a side-effect, because Map-like declarations inside of SpEL read like JSON, as the following example shows:
492+
Expressions can be used to invoke functions, evaluate conditionals, and construct values.
493+
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:
466494

467495
[source,java]
468496
----
@@ -473,12 +501,14 @@ public interface PersonRepository extends MongoRepository<Person, String> {
473501
}
474502
----
475503

476-
SpEL in query strings can be a powerful way to enhance queries.However, they can also accept a broad range of unwanted arguments.
504+
SpEL in query strings can be a powerful way to enhance queries.
505+
However, they can also accept a broad range of unwanted arguments.
477506
You should make sure to sanitize strings before passing them to the query to avoid unwanted changes to your query.
478507

479508
Expression support is extensible through the Query SPI: `org.springframework.data.repository.query.spi.EvaluationContextExtension`.
480-
The Query SPI can contribute properties and functions and can customize the root object.Extensions are retrieved from the application context
481-
at the time of SpEL evaluation when the query is built.The following example shows how to use `EvaluationContextExtension`:
509+
The Query SPI can contribute properties and functions and can customize the root object.
510+
Extensions are retrieved from the application context at the time of SpEL evaluation when the query is built.
511+
The following example shows how to use `EvaluationContextExtension`:
482512

483513
[source,java]
484514
----
@@ -525,7 +555,9 @@ Page<Person> page = repository.findAll(person.lastname.contains("a"),
525555
PageRequest.of(0, 2, Direction.ASC, "lastname"));
526556
----
527557

528-
`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.
558+
`QPerson` is a class that is generated by the Java annotation post-processing tool.
559+
It is a `Predicate` that lets you write type-safe queries.
560+
Notice that there are no strings in the query other than the `C0123` value.
529561

530562
You can use the generated `Predicate` class by using the `QuerydslPredicateExecutor` interface, which the following listing shows:
531563

@@ -558,11 +590,16 @@ public interface PersonRepository extends MongoRepository<Person, String>, Query
558590
[[mongodb.repositories.queries.full-text]]
559591
=== Full-text Search Queries
560592

561-
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 "`<<mapping-usage-indexes.text-index>>`" to learn how to create a full-text index).
593+
MongoDB's full-text search feature is store-specific and, therefore, can be found on `MongoRepository` rather than on the more general `CrudRepository`.
594+
We need a document with a full-text index (see "`<<mapping-usage-indexes.text-index>>`" to learn how to create a full-text index).
562595

563-
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:
596+
Additional methods on `MongoRepository` take `TextCriteria` as an input parameter.
597+
In addition to those explicit methods, it is also possible to add a `TextCriteria`-derived repository method.
598+
The criteria are added as an additional `AND` criteria.
599+
Once the entity contains a `@TextScore`-annotated property, the document's full-text score can be retrieved.
600+
Furthermore, the `@TextScore` annotated also makes it possible to sort by the document's score, as the following example shows:
564601

565-
[source, java]
602+
[source,java]
566603
----
567604
@Document
568605
class FullTextDocument {
@@ -602,7 +639,11 @@ include::./mongo-repositories-aggregation.adoc[]
602639
[[mongodb.repositories.misc.cdi-integration]]
603640
== CDI Integration
604641

605-
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:
642+
Instances of the repository interfaces are usually created by a container, and Spring is the most natural choice when working with Spring Data.
643+
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.
644+
The extension is part of the JAR.
645+
To activate it, drop the Spring Data MongoDB JAR into your classpath.
646+
You can now set up the infrastructure by implementing a CDI Producer for the `MongoTemplate`, as the following example shows:
606647

607648
[source,java]
608649
----
@@ -618,7 +659,8 @@ class MongoTemplateProducer {
618659
}
619660
----
620661

621-
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:
662+
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.
663+
Thus, obtaining an instance of a Spring Data repository is a matter of declaring an `@Inject`-ed property, as the following example shows:
622664

623665
[source,java]
624666
----

0 commit comments

Comments
 (0)