DATAMONGO-1974 - Full editing pass for Spring Data MongoDB.
Full editing pass of the Spring Data MongoDB reference guide. I also adjusted index.adoc to work with the changes I made to the build project, so that we get Epub and PDF as well as HTML. Original pull request: #559.
This commit is contained in:
BIN
src/main/asciidoc/images/epub-cover.png
Normal file
BIN
src/main/asciidoc/images/epub-cover.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 64 KiB |
12
src/main/asciidoc/images/epub-cover.svg
Normal file
12
src/main/asciidoc/images/epub-cover.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 8.9 KiB |
@@ -1,48 +1,47 @@
|
||||
= Spring Data MongoDB - Reference Documentation
|
||||
Mark Pollack; Thomas Risberg; Oliver Gierke; Costin Leau; Jon Brisbin; Thomas Darimont; Christoph Strobl; Mark Paluch
|
||||
Mark Pollack; Thomas Risberg; Oliver Gierke; Costin Leau; Jon Brisbin; Thomas Darimont; Christoph Strobl; Mark Paluch; Jay Bryant
|
||||
:revnumber: {version}
|
||||
:revdate: {localdate}
|
||||
:toc:
|
||||
:toc-placement!:
|
||||
:linkcss:
|
||||
:doctype: book
|
||||
:docinfo: shared
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:source-highlighter: prettify
|
||||
:icons: font
|
||||
:imagesdir: images
|
||||
ifdef::backend-epub3[:front-cover-image: image:epub-cover.png[Front Cover,1050,1600]]
|
||||
:spring-data-commons-docs: ../../../../spring-data-commons/src/main/asciidoc
|
||||
|
||||
(C) 2008-2018 The original authors.
|
||||
|
||||
NOTE: _Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically._
|
||||
|
||||
toc::[]
|
||||
NOTE: Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
|
||||
|
||||
include::preface.adoc[]
|
||||
|
||||
:leveloffset: +1
|
||||
include::new-features.adoc[]
|
||||
include::{spring-data-commons-docs}/dependencies.adoc[]
|
||||
include::{spring-data-commons-docs}/repositories.adoc[]
|
||||
:leveloffset: -1
|
||||
include::new-features.adoc[leveloffset=+1]
|
||||
include::{spring-data-commons-docs}/dependencies.adoc[leveloffset=+1]
|
||||
include::{spring-data-commons-docs}/repositories.adoc[leveloffset=+1]
|
||||
|
||||
[[reference]]
|
||||
= Reference Documentation
|
||||
|
||||
:leveloffset: +1
|
||||
include::reference/introduction.adoc[]
|
||||
include::reference/mongodb.adoc[]
|
||||
include::reference/mongo-repositories.adoc[]
|
||||
include::{spring-data-commons-docs}/auditing.adoc[]
|
||||
include::reference/mongo-auditing.adoc[]
|
||||
include::reference/mapping.adoc[]
|
||||
include::reference/cross-store.adoc[]
|
||||
include::reference/logging.adoc[]
|
||||
include::reference/jmx.adoc[]
|
||||
include::reference/mongo-3.adoc[]
|
||||
:leveloffset: -1
|
||||
include::reference/introduction.adoc[leveloffset=+1]
|
||||
include::reference/mongodb.adoc[leveloffset=+1]
|
||||
include::reference/mongo-repositories.adoc[leveloffset=+1]
|
||||
include::{spring-data-commons-docs}/auditing.adoc[leveloffset=+1]
|
||||
include::reference/mongo-auditing.adoc[leveloffset=+1]
|
||||
include::reference/mapping.adoc[leveloffset=+1]
|
||||
include::reference/cross-store.adoc[leveloffset=+1]
|
||||
include::reference/logging.adoc[leveloffset=+1]
|
||||
include::reference/jmx.adoc[leveloffset=+1]
|
||||
include::reference/mongo-3.adoc[leveloffset=+1]
|
||||
|
||||
[[appendix]]
|
||||
= Appendix
|
||||
|
||||
:numbered!:
|
||||
:leveloffset: +1
|
||||
include::{spring-data-commons-docs}/repository-namespace-reference.adoc[]
|
||||
include::{spring-data-commons-docs}/repository-populator-namespace-reference.adoc[]
|
||||
include::{spring-data-commons-docs}/repository-query-keywords-reference.adoc[]
|
||||
include::{spring-data-commons-docs}/repository-query-return-types-reference.adoc[]
|
||||
:leveloffset: -1
|
||||
include::{spring-data-commons-docs}/repository-namespace-reference.adoc[leveloffset=+1]
|
||||
include::{spring-data-commons-docs}/repository-populator-namespace-reference.adoc[leveloffset=+1]
|
||||
include::{spring-data-commons-docs}/repository-query-keywords-reference.adoc[leveloffset=+1]
|
||||
include::{spring-data-commons-docs}/repository-query-return-types-reference.adoc[leveloffset=+1]
|
||||
|
||||
@@ -2,45 +2,45 @@
|
||||
= New & Noteworthy
|
||||
|
||||
[[new-features.1-10-0]]
|
||||
== What's new in Spring Data MongoDB 1.10
|
||||
== What's New in Spring Data MongoDB 1.10
|
||||
* Compatible with MongoDB Server 3.4 and the MongoDB Java Driver 3.4.
|
||||
* New annotations for `@CountQuery`, `@DeleteQuery` and `@ExistsQuery`.
|
||||
* New annotations for `@CountQuery`, `@DeleteQuery`, and `@ExistsQuery`.
|
||||
* Extended support for MongoDB 3.2 and MongoDB 3.4 aggregation operators (see <<mongo.aggregation.supported-aggregation-operations>>).
|
||||
* Support partial filter expression when creating indexes.
|
||||
* Publish lifecycle events when loading/converting ``DBRef``s.
|
||||
* Support for partial filter expression when creating indexes.
|
||||
* Publishing lifecycle events when loading or converting `DBRef` instances.
|
||||
* Added any-match mode for Query By Example.
|
||||
* Support for `$caseSensitive` and `$diacriticSensitive` text search.
|
||||
* Support for GeoJSON Polygon with hole.
|
||||
* Performance improvements by bulk fetching ``DBRef``s.
|
||||
* Performance improvements by bulk-fetching `DBRef` instances.
|
||||
* Multi-faceted aggregations using `$facet`, `$bucket`, and `$bucketAuto` with `Aggregation`.
|
||||
|
||||
[[new-features.1-9-0]]
|
||||
== What's new in Spring Data MongoDB 1.9
|
||||
* The following annotations have been enabled to build own, composed annotations: `@Document`, `@Id`, `@Field`, `@Indexed`, `@CompoundIndex`, `@GeoSpatialIndexed`, `@TextIndexed`, `@Query`, `@Meta`.
|
||||
== What's New in Spring Data MongoDB 1.9
|
||||
* The following annotations have been enabled to build your own composed annotations: `@Document`, `@Id`, `@Field`, `@Indexed`, `@CompoundIndex`, `@GeoSpatialIndexed`, `@TextIndexed`, `@Query`, and `@Meta`.
|
||||
* Support for <<projections>> in repository query methods.
|
||||
* Support for <<query-by-example>>.
|
||||
* Out-of-the-box support for `java.util.Currency` in object mapping.
|
||||
* Add support for the bulk operations introduced in MongoDB 2.6.
|
||||
* Support for the bulk operations introduced in MongoDB 2.6.
|
||||
* Upgrade to Querydsl 4.
|
||||
* Assert compatibility with MongoDB 3.0 and MongoDB Java Driver 3.2 (see: <<mongo.mongo-3>>).
|
||||
|
||||
[[new-features.1-8-0]]
|
||||
== What's new in Spring Data MongoDB 1.8
|
||||
== What's New in Spring Data MongoDB 1.8
|
||||
|
||||
* `Criteria` offers support for creating `$geoIntersects`.
|
||||
* Support http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/expressions.html[SpEL expressions] in `@Query`.
|
||||
* `MongoMappingEvents` expose the collection name they are issued for.
|
||||
* Support for http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/expressions.html[SpEL expressions] in `@Query`.
|
||||
* `MongoMappingEvents` expose the collection name for which they are issued.
|
||||
* Improved support for `<mongo:mongo-client credentials="..." />`.
|
||||
* Improved index creation failure error message.
|
||||
|
||||
[[new-features.1-7-0]]
|
||||
== What's new in Spring Data MongoDB 1.7
|
||||
== What's New in Spring Data MongoDB 1.7
|
||||
|
||||
* Assert compatibility with MongoDB 3.0 and MongoDB Java Driver 3-beta3 (see: <<mongo.mongo-3>>).
|
||||
* Support JSR-310 and ThreeTen back-port date/time types.
|
||||
* Allow `Stream` as query method return type (see: <<mongodb.repositories.queries>>).
|
||||
* Added http://geojson.org/[GeoJSON] support in both domain types and queries (see: <<mongo.geo-json>>).
|
||||
* Allow `Stream` as a query method return type (see: <<mongodb.repositories.queries>>).
|
||||
* http://geojson.org/[GeoJSON] support in both domain types and queries (see: <<mongo.geo-json>>).
|
||||
* `QueryDslPredicateExcecutor` now supports `findAll(OrderSpecifier<?>… orders)`.
|
||||
* Support calling JavaScript functions via <<mongo.server-side-scripts>>.
|
||||
* Improve support for `CONTAINS` keyword on collection like properties.
|
||||
* Support for `$bit`, `$mul` and `$position` operators to `Update`.
|
||||
|
||||
* Support calling JavaScript functions with <<mongo.server-side-scripts>>.
|
||||
* Improve support for `CONTAINS` keyword on collection-like properties.
|
||||
* Support for `$bit`, `$mul`, and `$position` operators to `Update`.
|
||||
|
||||
@@ -1,59 +1,60 @@
|
||||
[[preface]]
|
||||
= Preface
|
||||
|
||||
The Spring Data MongoDB project applies core Spring concepts to the development of solutions using the MongoDB document style data store. We provide a "template" as a high-level abstraction for storing and querying documents. You will notice similarities to the JDBC support in the Spring Framework.
|
||||
The Spring Data MongoDB project applies core Spring concepts to the development of solutions that use the MongoDB document style data store. We provide a "`template`" as a high-level abstraction for storing and querying documents. You may notice similarities to the JDBC support provided by the Spring Framework.
|
||||
|
||||
This document is the reference guide for Spring Data - Document Support. It explains Document module concepts and semantics and the syntax for various store namespaces.
|
||||
This document is the reference guide for Spring Data - Document Support. It explains Document module concepts and semantics and syntax for various store namespaces.
|
||||
|
||||
This section provides some basic introduction to Spring and Document databases. The rest of the document refers only to Spring Data MongoDB features and assumes the user is familiar with MongoDB and Spring concepts.
|
||||
|
||||
[[get-started:first-steps:spring]]
|
||||
== Knowing Spring
|
||||
Spring Data uses Spring framework's http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/spring-core.html[core] functionality, such as the http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/beans.html[IoC] container, http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/validation.html#core-convert[type conversion system], http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/expressions.html[expression language], http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/jmx.html[JMX integration], and portable http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/dao.html#dao-exceptions[DAO exception hierarchy]. While it is not important to know the Spring APIs, understanding the concepts behind them is. At a minimum, the idea behind IoC should be familiar for whatever IoC container you choose to use.
|
||||
== Learning Spring
|
||||
|
||||
The core functionality of the MongoDB support can be used directly, with no need to invoke the IoC services of the Spring Container. This is much like `JdbcTemplate` which can be used 'standalone' without any other services of the Spring container. To leverage all the features of Spring Data MongoDB, such as the repository support, you will need to configure some parts of the library using Spring.
|
||||
Spring Data uses Spring framework's http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/core.html[core] functionality, including:
|
||||
|
||||
To learn more about Spring, you can refer to the comprehensive (and sometimes disarming) documentation that explains in detail the Spring Framework. There are a lot of articles, blog entries and books on the matter - take a look at the Spring framework http://spring.io/docs[home page] for more information.
|
||||
* http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/core.html#beans[IoC] container
|
||||
* http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/core.html#validation[type conversion system]
|
||||
* http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/core.html#expressions[expression language]
|
||||
* http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/integration.html#jmx[JMX integration]
|
||||
* http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/data-access.html#dao-exceptions[DAO exception hierarchy].
|
||||
|
||||
While you need not know the Spring APIs, understanding the concepts behind them is important. At a minimum, the idea behind Inversion of Control (IoC) should be familiar, and you should be familiar with whatever IoC container you choose to use.
|
||||
|
||||
The core functionality of the MongoDB support can be used directly, with no need to invoke the IoC services of the Spring Container. This is much like `JdbcTemplate`, which can be used "'standalone'" without any other services of the Spring container. To leverage all the features of Spring Data MongoDB, such as the repository support, you need to configure some parts of the library to use Spring.
|
||||
|
||||
To learn more about Spring, you can refer to the comprehensive documentation that explains the Spring Framework in detail. There are a lot of articles, blog entries, and books on the subject. See the Spring framework http://spring.io/docs[home page] for more information.
|
||||
|
||||
[[get-started:first-steps:nosql]]
|
||||
== Knowing NoSQL and Document databases
|
||||
NoSQL stores have taken the storage world by storm. It is a vast domain with a plethora of solutions, terms and patterns (to make things worse even the term itself has multiple http://www.google.com/search?q=nosoql+acronym[meanings]). While some of the principles are common, it is crucial that the user is familiar to some degree with MongoDB. The best way to get acquainted to this solutions is to read their documentation and follow their examples - it usually doesn't take more then 5-10 minutes to go through them and if you are coming from an RDMBS-only background many times these exercises can be an eye opener.
|
||||
== Learning NoSQL and Document databases
|
||||
NoSQL stores have taken the storage world by storm. It is a vast domain with a plethora of solutions, terms, and patterns (to make things worse, even the term itself has multiple http://www.google.com/search?q=nosoql+acronym[meanings]). While some of the principles are common, you must be familiar with MongoDB to some degree. The best way to get acquainted is to read the documentation and follow the examples. It usually does not take more then 5-10 minutes to go through them and, especially if you are coming from an RDMBS-only background, these exercises can be an eye opener.
|
||||
|
||||
The jumping off ground for learning about MongoDB is http://www.mongodb.org/[www.mongodb.org]. Here is a list of other useful resources:
|
||||
The starting point for learning about MongoDB is http://www.mongodb.org/[www.mongodb.org]. Here is a list of other useful resources:
|
||||
|
||||
* The http://docs.mongodb.org/manual/[manual] introduces MongoDB and contains links to getting started guides, reference documentation and tutorials.
|
||||
* The http://docs.mongodb.org/manual/[manual] introduces MongoDB and contains links to getting started guides, reference documentation, and tutorials.
|
||||
* The http://try.mongodb.org/[online shell] provides a convenient way to interact with a MongoDB instance in combination with the online http://docs.mongodb.org/manual/tutorial/getting-started/[tutorial.]
|
||||
* MongoDB http://docs.mongodb.org/ecosystem/drivers/java/[Java Language Center]
|
||||
* Several http://www.mongodb.org/books[books] available for purchase
|
||||
* Karl Seguin's online book: http://openmymind.net/mongodb.pdf[The Little MongoDB Book]
|
||||
* MongoDB http://docs.mongodb.org/ecosystem/drivers/java/[Java Language Center].
|
||||
* Several http://www.mongodb.org/books[books] you can purchase.
|
||||
* Karl Seguin's online book: http://openmymind.net/mongodb.pdf[The Little MongoDB Book].
|
||||
|
||||
[[requirements]]
|
||||
== Requirements
|
||||
|
||||
Spring Data MongoDB 1.x binaries requires JDK level 6.0 and above, and http://spring.io/docs[Spring Framework] {springVersion} and above.
|
||||
The Spring Data MongoDB 1.x binaries require JDK level 6.0 and above and http://spring.io/docs[Spring Framework] {springVersion} and above.
|
||||
|
||||
In terms of document stores, http://www.mongodb.org/[MongoDB] at least 2.6.
|
||||
|
||||
== Additional Help Resources
|
||||
|
||||
Learning a new framework is not always straight forward. In this section, we try to provide what we think is an easy to follow guide for starting with Spring Data MongoDB module. However, if you encounter issues or you are just looking for an advice, feel free to use one of the links below:
|
||||
In terms of document stores, you need at least version 2.6 of http://www.mongodb.org/[MongoDB].
|
||||
|
||||
[[get-started:help]]
|
||||
=== Support
|
||||
== Additional Help Resources
|
||||
|
||||
There are a few support options available:
|
||||
Learning a new framework is not always straightforward. In this section, we try to provide what we think is an easy-to-follow guide for starting with the Spring Data MongoDB module. However, if you encounter issues or you need advice, feel free to use one of the following links:
|
||||
|
||||
[[get-started:help:community]]
|
||||
==== Community Forum
|
||||
|
||||
Spring Data on Stackoverflow http://stackoverflow.com/questions/tagged/spring-data[Stackoverflow] is a tag for all Spring Data (not just Document) users to share information and help each other. Note that registration is needed *only* for posting.
|
||||
Community Forum :: Spring Data on http://stackoverflow.com/questions/tagged/spring-data[Stack Overflow] is a tag for all Spring Data (not just Document) users to share information and help each other. Note that registration is needed only for posting.
|
||||
|
||||
[[get-started:help:professional]]
|
||||
==== Professional Support
|
||||
|
||||
Professional, from-the-source support, with guaranteed response time, is available from http://pivotal.io/[Pivotal Sofware, Inc.], the company behind Spring Data and Spring.
|
||||
Professional Support :: Professional, from-the-source support, with guaranteed response time, is available from http://pivotal.io/[Pivotal Sofware, Inc.], the company behind Spring Data and Spring.
|
||||
|
||||
[[get-started:up-to-date]]
|
||||
=== Following Development
|
||||
== Following Development
|
||||
|
||||
For information on the Spring Data Mongo source code repository, nightly builds and snapshot artifacts please see the http://projects.spring.io/spring-data-mongodb/[Spring Data Mongo homepage]. You can help make Spring Data best serve the needs of the Spring community by interacting with developers through the Community on http://stackoverflow.com/questions/tagged/spring-data[Stackoverflow]. To follow developer activity look for the mailing list information on the Spring Data Mongo homepage. If you encounter a bug or want to suggest an improvement, please create a ticket on the Spring Data issue https://jira.spring.io/browse/DATAMONGO[tracker]. To stay up to date with the latest news and announcements in the Spring eco system, subscribe to the Spring Community http://spring.io[Portal]. Lastly, you can follow the Spring http://spring.io/blog[blog ]or the project team on Twitter (http://twitter.com/SpringData[SpringData]).
|
||||
For information on the Spring Data Mongo source code repository, nightly builds, and snapshot artifacts, see the Spring Data Mongo http://projects.spring.io/spring-data-mongodb/[homepage]. You can help make Spring Data best serve the needs of the Spring community by interacting with developers through the Community on http://stackoverflow.com/questions/tagged/spring-data[Stack Overflow]. To follow developer activity, look for the mailing list information on the Spring Data Mongo https://projects.spring.io/spring-data-mongodb/[homepage]. If you encounter a bug or want to suggest an improvement, please create a ticket on the Spring Data issue https://jira.spring.io/browse/DATAMONGO[tracker]. To stay up to date with the latest news and announcements in the Spring eco system, subscribe to the Spring Community http://spring.io[Portal]. You can also follow the Spring http://spring.io/blog[blog ]or the project team on Twitter (http://twitter.com/SpringData[SpringData]).
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
[[mongo.cross.store]]
|
||||
= Cross Store support
|
||||
= Cross Store Support
|
||||
|
||||
Sometimes you need to store data in multiple data stores and these data stores can be of different types. One might be relational while the other a document store. For this use case we have created a separate module in the MongoDB support that handles what we call cross-store support. The current implementation is based on JPA as the driver for the relational database and we allow select fields in the Entities to be stored in a Mongo database. In addition to allowing you to store your data in two stores we also coordinate persistence operations for the non-transactional MongoDB store with the transaction life-cycle for the relational database.
|
||||
|
||||
[[mongodb_cross-store-configuration]]
|
||||
== Cross Store Configuration
|
||||
|
||||
Assuming that you have a working JPA application and would like to add some cross-store persistence for MongoDB. What do you have to add to your configuration?
|
||||
Assuming that you have a working JPA application and would like to add some cross-store persistence for MongoDB, what do you have to add to your configuration?
|
||||
|
||||
First of all you need to add a dependency on the module. Using Maven this is done by adding a dependency to your pom:
|
||||
First, you need to add a dependency on the cross-store module. If you use Maven, you can add the following dependency to your pom:
|
||||
|
||||
.Example Maven pom.xml with spring-data-mongodb-cross-store dependency
|
||||
.Example Maven pom.xml with `spring-data-mongodb-cross-store` dependency
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
@@ -33,7 +33,7 @@ First of all you need to add a dependency on the module. Using Maven this is do
|
||||
----
|
||||
====
|
||||
|
||||
Once this is done we need to enable AspectJ for the project. The cross-store support is implemented using AspectJ aspects so by enabling compile time AspectJ support the cross-store features will become available to your project. In Maven you would add an additional plugin to the <build> section of the pom:
|
||||
Once you have added the dependency, you need to enable AspectJ for the project. The cross-store support is implemented with AspectJ aspects so, if you enable compile-time AspectJ support, the cross-store features become available to your project. In Maven, you would add an additional plugin to the `<build>` section of the pom, as follows:
|
||||
|
||||
.Example Maven pom.xml with AspectJ plugin enabled
|
||||
====
|
||||
@@ -103,7 +103,7 @@ Once this is done we need to enable AspectJ for the project. The cross-store sup
|
||||
----
|
||||
====
|
||||
|
||||
Finally, you need to configure your project to use MongoDB and also configure the aspects that are used. The following XML snippet should be added to your application context:
|
||||
Finally, you need to configure your project to use MongoDB and also configure which aspects are used. You should add the following XML snippet to your application context:
|
||||
|
||||
.Example application context with MongoDB and cross-store aspect support
|
||||
====
|
||||
@@ -157,7 +157,13 @@ Finally, you need to configure your project to use MongoDB and also configure th
|
||||
[[mongodb_cross-store-application]]
|
||||
== Writing the Cross Store Application
|
||||
|
||||
We are assuming that you have a working JPA application so we will only cover the additional steps needed to persist part of your Entity in your Mongo database. First you need to identify the field you want persisted. It should be a domain class and follow the general rules for the Mongo mapping support covered in previous chapters. The field you want persisted in MongoDB should be annotated using the `@RelatedDocument` annotation. That is really all you need to do!. The cross-store aspects take care of the rest. This includes marking the field with `@Transient` so it won't be persisted using JPA, keeping track of any changes made to the field value and writing them to the database on successful transaction completion, loading the document from MongoDB the first time the value is used in your application. Here is an example of a simple Entity that has a field annotated with `@RelatedDocument`.
|
||||
We assume that you have a working JPA application, so we cover only the additional steps needed to persist part of your entity in your Mongo database. To do so, you need to identify the field you want to persist. It should be a domain class and follow the general rules for the Mongo mapping support covered in previous chapters. The field you want to persist in MongoDB should be annotated with the `@RelatedDocument` annotation. That is really all you need to do. The cross-store aspects take care of the rest, including:
|
||||
|
||||
* Marking the field with `@Transient` so that it will not be persisted by JPA
|
||||
* Keeping track of any changes made to the field value and writing them to the database on successful transaction completion
|
||||
* Loading the document from MongoDB the first time the value is used in your application.
|
||||
|
||||
The following example shows an entity that has a field annotated with `@RelatedDocument`:
|
||||
|
||||
.Example of Entity with @RelatedDocument
|
||||
====
|
||||
@@ -182,7 +188,9 @@ public class Customer {
|
||||
----
|
||||
====
|
||||
|
||||
.Example of domain class to be stored as document
|
||||
The following example shows a domain class that is to be stored as a `Document`:
|
||||
|
||||
.Example of a domain class to be stored as a Document
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@@ -214,7 +222,7 @@ public class SurveyInfo {
|
||||
----
|
||||
====
|
||||
|
||||
Once the SurveyInfo has been set on the Customer object above the MongoTemplate that was configured above is used to save the SurveyInfo along with some metadata about the JPA Entity is stored in a MongoDB collection named after the fully qualified name of the JPA Entity class. The following code:
|
||||
In the preceding example, once the `SurveyInfo` has been set on the `Customer` object, the `MongoTemplate` that was configured previously is used to save the `SurveyInfo` (along with some metadata about the JPA Entity) in a MongoDB collection named after the fully qualified name of the JPA Entity class. The following code shows how to configure a JPA entity for cross-store persistence with MongoDB:
|
||||
|
||||
.Example of code using the JPA Entity configured for cross-store persistence
|
||||
====
|
||||
@@ -232,7 +240,7 @@ customerRepository.save(customer);
|
||||
----
|
||||
====
|
||||
|
||||
Executing the code above results in the following JSON document stored in MongoDB.
|
||||
Running the preceding above results in the following JSON document being stored in MongoDB:
|
||||
|
||||
.Example of JSON document stored in MongoDB
|
||||
====
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
This part of the reference documentation explains the core functionality offered by Spring Data MongoDB.
|
||||
|
||||
<<mongo.core>> introduces the MongoDB module feature set.
|
||||
|
||||
<<mongo.repositories>> introduces the repository support for MongoDB.
|
||||
"`<<mongo.core>>`" introduces the MongoDB module feature set.
|
||||
|
||||
"`<<mongo.repositories>>`" introduces the repository support for MongoDB.
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[[mongo.jmx]]
|
||||
= JMX support
|
||||
|
||||
The JMX support for MongoDB exposes the results of executing the 'serverStatus' command on the admin database for a single MongoDB server instance. It also exposes an administrative MBean, MongoAdmin which will let you perform administrative operations such as drop or create a database. The JMX features build upon the JMX feature set available in the Spring Framework. See http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/jmx.html[here ] for more details.
|
||||
The JMX support for MongoDB exposes the results of executing the 'serverStatus' command on the admin database for a single MongoDB server instance. It also exposes an administrative MBean, `MongoAdmin`, that lets you perform administrative operations, such as dropping or creating a database. The JMX features build upon the JMX feature set available in the Spring Framework. See http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/jmx.html[here] for more details.
|
||||
|
||||
[[mongodb:jmx-configuration]]
|
||||
== MongoDB JMX Configuration
|
||||
|
||||
Spring's Mongo namespace enables you to easily enable JMX functionality
|
||||
Spring's Mongo namespace lets you enable JMX functionality, as the following example shows:
|
||||
|
||||
.XML schema to configure MongoDB
|
||||
====
|
||||
@@ -47,18 +47,18 @@ Spring's Mongo namespace enables you to easily enable JMX functionality
|
||||
----
|
||||
====
|
||||
|
||||
This will expose several MBeans
|
||||
The preceding code exposes several MBeans:
|
||||
|
||||
* AssertMetrics
|
||||
* BackgroundFlushingMetrics
|
||||
* BtreeIndexCounters
|
||||
* ConnectionMetrics
|
||||
* GlobalLoclMetrics
|
||||
* MemoryMetrics
|
||||
* OperationCounters
|
||||
* ServerInfo
|
||||
* MongoAdmin
|
||||
* `AssertMetrics`
|
||||
* `BackgroundFlushingMetrics`
|
||||
* `BtreeIndexCounters`
|
||||
* `ConnectionMetrics`
|
||||
* `GlobalLockMetrics`
|
||||
* `MemoryMetrics`
|
||||
* `OperationCounters`
|
||||
* `ServerInfo`
|
||||
* `MongoAdmin`
|
||||
|
||||
This is shown below in a screenshot from JConsole
|
||||
The following screenshot from JConsole shows the resulting configuration:
|
||||
|
||||
image::jconsole.png[]
|
||||
image::jconsole.png[]
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
[[mapping-chapter]]
|
||||
= Mapping
|
||||
|
||||
Rich mapping support is provided by the `MappingMongoConverter`. `MappingMongoConverter` has a rich metadata model that provides a full feature set of functionality to map domain objects to MongoDB documents.The mapping metadata model is populated using annotations on your domain objects. However, the infrastructure is not limited to using annotations as the only source of metadata information. The `MappingMongoConverter` also allows you to map objects to documents without providing any additional metadata, by following a set of conventions.
|
||||
Rich mapping support is provided by the `MappingMongoConverter`. `MappingMongoConverter` has a rich metadata model that provides a full feature set to map domain objects to MongoDB documents. The mapping metadata model is populated by using annotations on your domain objects. However, the infrastructure is not limited to using annotations as the only source of metadata information. The `MappingMongoConverter` also lets you map objects to documents without providing any additional metadata, by following a set of conventions.
|
||||
|
||||
In this section we will describe the features of the `MappingMongoConverter`. How to use conventions for mapping objects to documents and how to override those conventions with annotation based mapping metadata.
|
||||
This section describes the features of the `MappingMongoConverter`, including how to use conventions for mapping objects to documents and how to override those conventions with annotation-based mapping metadata.
|
||||
|
||||
NOTE: `SimpleMongoConverter` has been deprecated in Spring Data MongoDB M3 as all of its functionality has been subsumed into `MappingMongoConverter`.
|
||||
|
||||
[[mapping-conventions]]
|
||||
== Convention based Mapping
|
||||
== Convention-based Mapping
|
||||
|
||||
`MappingMongoConverter` has a few conventions for mapping objects to documents when no additional mapping metadata is provided. The conventions are:
|
||||
|
||||
* The short Java class name is mapped to the collection name in the following manner. The class `com.bigbank.SavingsAccount` maps to `savingsAccount` collection name.
|
||||
* All nested objects are stored as nested objects in the document and *not* as DBRefs
|
||||
* The converter will use any Spring Converters registered with it to override the default mapping of object properties to document field/values.
|
||||
* The fields of an object are used to convert to and from fields in the document. Public JavaBean properties are not used.
|
||||
* You can have a single non-zero argument constructor whose constructor argument names match top level field names of document, that constructor will be used. Otherwise the zero arg constructor will be used. if there is more than one non-zero argument constructor an exception will be thrown.
|
||||
* The short Java class name is mapped to the collection name in the following manner. The class `com.bigbank.SavingsAccount` maps to the `savingsAccount` collection name.
|
||||
* All nested objects are stored as nested objects in the document and *not* as DBRefs.
|
||||
* The converter uses any Spring Converters registered with it to override the default mapping of object properties to document fields and values.
|
||||
* The fields of an object are used to convert to and from fields in the document. Public `JavaBean` properties are not used.
|
||||
* If you have a single non-zero-argument constructor whose constructor argument names match top-level field names of document, that constructor is used. Otherwise, the zero-argument constructor is used. If there is more than one non-zero-argument constructor, an exception will be thrown.
|
||||
|
||||
[[mapping.conventions.id-field]]
|
||||
=== How the `_id` field is handled in the mapping layer
|
||||
=== How the `_id` field is handled in the mapping layer.
|
||||
|
||||
MongoDB requires that you have an `_id` field for all documents. If you don't provide one the driver will assign a ObjectId with a generated value. The "_id" field can be of any type the, other than arrays, so long as it is unique. The driver naturally supports all primitive types and Dates. When using the `MappingMongoConverter` there are certain rules that govern how properties from the Java class is mapped to this `_id` field.
|
||||
|
||||
@@ -60,10 +60,12 @@ The following outlines what type conversion, if any, will be done on the propert
|
||||
When querying and updating `MongoTemplate` will use the converter to handle conversions of the `Query` and `Update` objects that correspond to the above rules for saving documents so field names and types used in your queries will be able to match what is in your domain classes.
|
||||
|
||||
[[mapping-conversion]]
|
||||
== Data mapping and type conversion
|
||||
== Data Mapping and Type Conversion
|
||||
|
||||
This section explain how types are mapped to a MongoDB representation and vice versa. Spring Data MongoDB supports all types that can be represented as BSON, MongoDB's internal document format.
|
||||
In addition to these types, Spring Data MongoDB provides a set of built-in converters to map additional types. You can provide your own converters to adjust type conversion, see <<mapping-explicit-converters>> for further details.
|
||||
This section explains how types are mapped to and from a MongoDB representation. Spring Data MongoDB supports all types that can be represented as BSON, MongoDB's internal document format.
|
||||
In addition to these types, Spring Data MongoDB provides a set of built-in converters to map additional types. You can provide your own converters to adjust type conversion. See <<mapping-explicit-converters>> for further details.
|
||||
|
||||
The following provides samples of each available type conversion:
|
||||
|
||||
[cols="3,1,6", options="header"]
|
||||
.Type
|
||||
@@ -250,9 +252,9 @@ calling `get()` before the actual conversion
|
||||
[[mapping-configuration]]
|
||||
== Mapping Configuration
|
||||
|
||||
Unless explicitly configured, an instance of `MappingMongoConverter` is created by default when creating a `MongoTemplate`. You can create your own instance of the `MappingMongoConverter` so as to tell it where to scan the classpath at startup your domain classes in order to extract metadata and construct indexes. Also, by creating your own instance you can register Spring converters to use for mapping specific classes to and from the database.
|
||||
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 to 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.Mongo` and MongoTemplate either using Java or XML based metadata. Here is an example using Spring's Java based configuration
|
||||
You can configure the `MappingMongoConverter` as well as `com.mongodb.Mongo` and MongoTemplate by using either Java-based or XML-based metadata. The following example uses Spring's Java-based configuration:
|
||||
|
||||
.@Configuration class to configure MongoDB mapping support
|
||||
====
|
||||
@@ -296,15 +298,15 @@ public class GeoSpatialAppConfig extends AbstractMongoConfiguration {
|
||||
----
|
||||
====
|
||||
|
||||
`AbstractMongoConfiguration` requires you to implement methods that define a `com.mongodb.Mongo` as well as provide a database name. `AbstractMongoConfiguration` also has a method you can override named `getMappingBasePackage(…)` which tells the converter where to scan for classes annotated with the `@Document` annotation.
|
||||
`AbstractMongoConfiguration` requires you to implement methods that define a `com.mongodb.Mongo` as well as provide a database name. `AbstractMongoConfiguration` 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 method afterMappingMongoConverterCreation. Also shown in the above example is a `LoggingEventListener` which logs `MongoMappingEvent` s that are posted onto Spring's `ApplicationContextEvent` infrastructure.
|
||||
You can add additional converters to the converter by overriding the `afterMappingMongoConverterCreation` method. Also shown in the preceding example is a `LoggingEventListener`, which logs `MongoMappingEvent` instances that are posted onto Spring's `ApplicationContextEvent` infrastructure.
|
||||
|
||||
NOTE: AbstractMongoConfiguration will create a MongoTemplate instance and registered with the container under the name `mongoTemplate`.
|
||||
NOTE: `AbstractMongoConfiguration` creates a `MongoTemplate` instance and registers it with the container under the name `mongoTemplate`.
|
||||
|
||||
You can also override the method `UserCredentials getUserCredentials()` to provide the username and password information to connect to the database.
|
||||
You can also override the `UserCredentials getUserCredentials()` method to provide the username and password information to connect to the database.
|
||||
|
||||
Spring's MongoDB namespace enables you to easily enable mapping functionality in XML
|
||||
Spring's MongoDB namespace lets you enable mapping functionality in XML, as the following example shows:
|
||||
|
||||
.XML schema to configure MongoDB mapping support
|
||||
====
|
||||
@@ -351,9 +353,9 @@ Spring's MongoDB namespace enables you to easily enable mapping functionality in
|
||||
The `base-package` property tells it where to scan for classes annotated with the `@org.springframework.data.mongodb.core.mapping.Document` annotation.
|
||||
|
||||
[[mapping-usage]]
|
||||
== Metadata based Mapping
|
||||
== Metadata-based Mapping
|
||||
|
||||
To take full advantage of the object mapping functionality inside the Spring Data/MongoDB support, you should annotate your mapped objects with the `@Document` annotation. Although it is not necessary for the mapping framework to have this annotation (your POJOs will be mapped correctly, even without any annotations), it allows the classpath scanner to find and pre-process your domain objects to extract the necessary metadata. If you don't use this annotation, your application will take a slight performance hit the first time you store a domain object because the mapping framework needs to build up its internal metadata model so it knows about the properties of your domain object and how to persist them.
|
||||
To take full advantage of the object mapping functionality inside the Spring Data MongoDB support, you should annotate your mapped objects with the `@Document` annotation. Although it is not necessary for the mapping framework to have this annotation (your POJOs are mapped correctly, even without any annotations), it lets the classpath scanner find and pre-process your domain objects to extract the necessary metadata. If you do not use this annotation, your application takes a slight performance hit the first time you store a domain object, because the mapping framework needs to build up its internal metadata model so that it knows about the properties of your domain object and how to persist them. The following example shows a domain object:
|
||||
|
||||
.Example domain object
|
||||
====
|
||||
@@ -378,28 +380,28 @@ 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.
|
||||
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.
|
||||
|
||||
IMPORTANT: Automatic index creation is only done for types annotated with `@Document`.
|
||||
|
||||
[[mapping-usage-annotations]]
|
||||
=== Mapping annotation overview
|
||||
=== Mapping Annotation Overview
|
||||
|
||||
The MappingMongoConverter can use metadata to drive the mapping of objects to documents. An overview of the annotations is provided below
|
||||
The MappingMongoConverter can use metadata to drive the mapping of objects to documents. The following annotations are available:
|
||||
|
||||
* `@Id` - applied at the field level to mark the field used for identity purpose.
|
||||
* `@Document` - applied at the class level to indicate this class is a candidate for mapping to the database. You can specify the name of the collection where the database will be stored.
|
||||
* `@DBRef` - applied at the field to indicate it is to be stored using a com.mongodb.DBRef.
|
||||
* `@Indexed` - applied at the field level to describe how to index the field.
|
||||
* `@CompoundIndex` - applied at the type level to declare Compound Indexes
|
||||
* `@GeoSpatialIndexed` - applied at the field level to describe how to geoindex the field.
|
||||
* `@TextIndexed` - applied at the field level to mark the field to be included in the text index.
|
||||
* `@Language` - applied at the field level to set the language override property for text index.
|
||||
* `@Transient` - by default all private fields are mapped to the document, this annotation excludes the field where it is applied from being stored in the database
|
||||
* `@PersistenceConstructor` - marks a given constructor - even a package protected one - to use when instantiating the object from the database. Constructor arguments are mapped by name to the key values in the retrieved DBObject.
|
||||
* `@Value` - this annotation is part of the Spring Framework . Within the mapping framework it can be applied to constructor arguments. This lets you use a Spring Expression Language statement to transform a key's value retrieved in the database before it is used to construct a domain object. In order to reference a property of a given document one has to use expressions like: `@Value("#root.myProperty")` where `root` refers to the root of the given document.
|
||||
* `@Field` - applied at the field level and described the name of the field as it will be represented in the MongoDB BSON document thus allowing the name to be different than the fieldname of the class.
|
||||
* `@Version` - applied at field level is used for optimistic locking and checked for modification on save operations. The initial value is `zero` which is bumped automatically on every update.
|
||||
* `@Id`: Applied at the field level to mark the field used for identity purpose.
|
||||
* `@Document`: Applied at the class level to indicate this class is a candidate for mapping to the database. You can specify the name of the collection where the database will be stored.
|
||||
* `@DBRef`: Applied at the field to indicate it is to be stored using a com.mongodb.DBRef.
|
||||
* `@Indexed`: Applied at the field level to describe how to index the field.
|
||||
* `@CompoundIndex`: Applied at the type level to declare Compound Indexes
|
||||
* `@GeoSpatialIndexed`: Applied at the field level to describe how to geoindex the field.
|
||||
* `@TextIndexed`: Applied at the field level to mark the field to be included in the text index.
|
||||
* `@Language`: Applied at the field level to set the language override property for text index.
|
||||
* `@Transient`: By default all private fields are mapped to the document, this annotation excludes the field where it is applied from being stored in the database
|
||||
* `@PersistenceConstructor`: Marks a given constructor - even a package protected one - to use when instantiating the object from the database. Constructor arguments are mapped by name to the key values in the retrieved DBObject.
|
||||
* `@Value`: This annotation is part of the Spring Framework . Within the mapping framework it can be applied to constructor arguments. This lets you use a Spring Expression Language statement to transform a key's value retrieved in the database before it is used to construct a domain object. In order to reference a property of a given document one has to use expressions like: `@Value("#root.myProperty")` where `root` refers to the root of the given document.
|
||||
* `@Field`: Applied at the field level and described the name of the field as it will be represented in the MongoDB BSON document thus allowing the name to be different than the fieldname of the class.
|
||||
* `@Version`: Applied at field level is used for optimistic locking and checked for modification on save operations. The initial value is `zero` which is bumped automatically on every update.
|
||||
|
||||
The mapping metadata infrastructure is defined in a separate spring-data-commons project that is technology agnostic. Specific subclasses are using in the MongoDB support to support annotation based metadata. Other strategies are also possible to put in place if there is demand.
|
||||
|
||||
@@ -534,7 +536,7 @@ public class Person {
|
||||
|
||||
NOTE: The text index feature is disabled by default for mongodb v.2.4.
|
||||
|
||||
Creating a text index allows accumulating several fields into a searchable full text index. It is only possible to have one text index per collection so all fields marked with `@TextIndexed` are combined into this index. Properties can be weighted to influence document score for ranking results. The default language for the text index is english, to change the default language set `@Document(language="spanish")` to any language you want. Using a property called `language` or `@Language` allows to define a language override on a per document base.
|
||||
Creating a text index allows accumulating several fields into a searchable full-text index. It is only possible to have one text index per collection, so all fields marked with `@TextIndexed` are combined into this index. Properties can be weighted to influence the document score for ranking results. The default language for the text index is English. To change the default language, set the `language` attribute to whichever language you want (for example,`@Document(language="spanish")`). Using a property called `language` or `@Language` lets you define a language override on a per document base. The following example shows how to created a text index and set the language to Spanish:
|
||||
|
||||
.Example Text Index Usage
|
||||
====
|
||||
@@ -561,9 +563,9 @@ class Nested {
|
||||
[[mapping-usage-references]]
|
||||
=== Using DBRefs
|
||||
|
||||
The mapping framework doesn't have to store child objects embedded within the document. You can also store them separately and use a DBRef to refer to that document. When the object is loaded from MongoDB, those references will be eagerly resolved and you will get back a mapped object that looks the same as if it had been stored embedded within your master document.
|
||||
The mapping framework does not have to store child objects embedded within the document. You can also store them separately and use a DBRef to refer to that document. When the object is loaded from MongoDB, those references are eagerly resolved so that you get back a mapped object that looks the same as if it had been stored embedded within your master document.
|
||||
|
||||
Here's an example of using a DBRef to refer to a specific document that exists independently of the object in which it is referenced (both classes are shown in-line for brevity's sake):
|
||||
The following example uses a DBRef to refer to a specific document that exists independently of the object in which it is referenced (both classes are shown in-line for brevity's sake):
|
||||
|
||||
====
|
||||
[source,java]
|
||||
@@ -589,27 +591,27 @@ public class Person {
|
||||
----
|
||||
====
|
||||
|
||||
There's no need to use something like `@OneToMany` because the mapping framework sees that you want a one-to-many relationship because there is a List of objects. When the object is stored in MongoDB, there will be a list of DBRefs rather than the `Account` objects themselves.
|
||||
You need not use `@OneToMany` or similar mechanisms because the List of objects tells the mapping framework sees that you want a one-to-many relationship. When the object is stored in MongoDB, there is a list of DBRefs rather than the `Account` objects themselves.
|
||||
|
||||
IMPORTANT: The mapping framework does not handle cascading saves. If you change an `Account` object that is referenced by a `Person` object, you must save the Account object separately. Calling `save` on the `Person` object will not automatically save the `Account` objects in the property `accounts`.
|
||||
IMPORTANT: The mapping framework does not handle cascading saves. If you change an `Account` object that is referenced by a `Person` object, you must save the `Account` object separately. Calling `save` on the `Person` object does not automatically save the `Account` objects in the `accounts` property.
|
||||
|
||||
[[mapping-usage-events]]
|
||||
=== Mapping Framework Events
|
||||
|
||||
Events are fired throughout the lifecycle of the mapping process. This is described in the <<mongodb.mapping-usage.events,Lifecycle Events>> section.
|
||||
|
||||
Simply declaring these beans in your Spring ApplicationContext will cause them to be invoked whenever the event is dispatched.
|
||||
Declaring these beans in your Spring ApplicationContext causes them to be invoked whenever the event is dispatched.
|
||||
|
||||
[[mapping-explicit-converters]]
|
||||
=== Overriding Mapping with explicit Converters
|
||||
=== Overriding Mapping with Explicit Converters
|
||||
|
||||
When storing and querying your objects it is convenient to have a `MongoConverter` instance handle the mapping of all Java types to DBObjects. However, sometimes you may want the `MongoConverter` s do most of the work but allow you to selectively handle the conversion for a particular type or to optimize performance.
|
||||
|
||||
To selectively handle the conversion yourself, register one or more one or more `org.springframework.core.convert.converter.Converter` instances with the MongoConverter.
|
||||
To selectively handle the conversion yourself, register one or more one or more `org.springframework.core.convert.converter.Converter` instances with the `MongoConverter`.
|
||||
|
||||
NOTE: Spring 3.0 introduced a core.convert package that provides a general type conversion system. This is described in detail in the Spring reference documentation section entitled http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/validation.html#core-convert[Spring Type Conversion].
|
||||
NOTE: Spring 3.0 introduced a core.convert package that provides a general type conversion system. This is described in detail in the Spring reference documentation section entitled http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/validation.html#core-convert["`Spring Type Conversion`"].
|
||||
|
||||
The method `customConversions` in `AbstractMongoConfiguration` can be used to configure Converters. The examples <<mapping-configuration,here>> at the beginning of this chapter show how to perform the configuration using Java and XML.
|
||||
You can use the `customConversions` method in `AbstractMongoConfiguration` to configure converters. The examples <<mapping-configuration, at the beginning of this chapter>> show how to perform the configuration using Java and XML.
|
||||
|
||||
Below is an example of a Spring Converter implementation that converts from a DBObject to a Person POJO.
|
||||
|
||||
|
||||
@@ -1,24 +1,26 @@
|
||||
[[mongo.mongo-3]]
|
||||
= MongoDB 3.0 Support
|
||||
|
||||
Spring Data MongoDB allows usage of both MongoDB Java driver generations 2 and 3 when connecting to a MongoDB 2.6/3.0 server running _MMap.v1_ or a MongoDB server 3.0 using _MMap.v1_ or the _WiredTiger_ storage engine.
|
||||
Spring Data MongoDB allows usage of both MongoDB Java driver generations 2 and 3 when connecting to a MongoDB 2.6/3.0 server running MMap.v1 or a MongoDB server 3.0 using MMap.v1 or the WiredTiger storage engine.
|
||||
|
||||
NOTE: Please refer to the driver and database specific documentation for major differences between those.
|
||||
NOTE: See the driver- and database-specific documentation for major differences between those engines.
|
||||
|
||||
NOTE: Operations that are no longer valid using a 3.x MongoDB Java driver have been deprecated within Spring Data and will be removed in a subsequent release.
|
||||
NOTE: Operations that are no longer valid when using a 3.x MongoDB Java driver have been deprecated within Spring Data and will be removed in a subsequent release.
|
||||
|
||||
== Using Spring Data MongoDB with MongoDB 3.0
|
||||
|
||||
The rest of this section describes how to use Spring Data MongoDB with MongoDB 3.0.
|
||||
|
||||
[[mongo.mongo-3.configuration]]
|
||||
=== Configuration Options
|
||||
|
||||
Some of the configuration options have been changed / removed for the _mongo-java-driver_. The following options will be ignored using the generation 3 driver:
|
||||
Some of the configuration options have been changed or removed for the `mongo-java-driver`. The following options are ignored when using the generation 3 driver:
|
||||
|
||||
* autoConnectRetry
|
||||
* maxAutoConnectRetryTime
|
||||
* slaveOk
|
||||
* `autoConnectRetry`
|
||||
* `maxAutoConnectRetryTime`
|
||||
* `slaveOk`
|
||||
|
||||
Generally it is recommended to use the `<mongo:mongo-client ... />` and `<mongo:client-options ... />` elements instead of `<mongo:mongo ... />` when doing XML based configuration, since those elements will only provide you with attributes valid for the 3 generation java driver.
|
||||
Generally, you should use the `<mongo:mongo-client ... />` and `<mongo:client-options ... />` elements instead of `<mongo:mongo ... />` when doing XML based configuration, since those elements provide you with attributes that are only valid for the third generation Java driver. The follwoing example shows how to configure a Mongo client connection:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
@@ -37,14 +39,14 @@ Generally it is recommended to use the `<mongo:mongo-client ... />` and `<mongo:
|
||||
----
|
||||
|
||||
[[mongo.mongo-3.write-concern]]
|
||||
=== WriteConcern and WriteConcernChecking
|
||||
=== `WriteConcern` and `WriteConcernChecking`
|
||||
|
||||
The `WriteConcern.NONE`, which had been used as default by Spring Data MongoDB, was removed in 3.0. Therefore in a MongoDB 3 environment the `WriteConcern` will be defaulted to `WriteConcern.UNACKNOWLEGED`. In case `WriteResultChecking.EXCEPTION` is enabled the `WriteConcern` will be altered to `WriteConcern.ACKNOWLEDGED` for write operations, as otherwise errors during execution would not be throw correctly, since simply not raised by the driver.
|
||||
`WriteConcern.NONE`, which had been used as the default by Spring Data MongoDB, was removed in 3.0. Therefore, in a MongoDB 3 environment, the `WriteConcern` defaults to `WriteConcern.UNACKNOWLEGED`. If `WriteResultChecking.EXCEPTION` is enabled, the `WriteConcern` is altered to `WriteConcern.ACKNOWLEDGED` for write operations. Otherwise, errors during execution would not be thrown correctly, since they are not raised by the driver.
|
||||
|
||||
[[mongo.mongo-3.authentication]]
|
||||
=== Authentication
|
||||
|
||||
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. Please use the `MongoClient` specific options for setting credentials via `MongoCredential` to provide authentication data.
|
||||
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 when setting credentials with `MongoCredential` to provide authentication data, as the following example shows:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -65,7 +67,7 @@ public class ApplicationContextEventTestsAppConfig extends AbstractMongoConfigur
|
||||
}
|
||||
----
|
||||
|
||||
In order to use authentication with XML configuration use the `credentials` attribue on `<mongo-client>`.
|
||||
In order to use authentication with XML configuration, you can use the `credentials` attribute on `<mongo-client>`, as the following example shows:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
@@ -82,14 +84,13 @@ In order to use authentication with XML configuration use the `credentials` attr
|
||||
----
|
||||
|
||||
[[mongo.mongo-3.misc]]
|
||||
=== Other things to be aware of
|
||||
=== Miscellaneous Details
|
||||
|
||||
This section covers additional things to keep in mind when using the 3.0 driver.
|
||||
This section covers briefly lists additional things to keep in mind when using the 3.0 driver:
|
||||
|
||||
* `IndexOperations.resetIndexCache()` is no longer supported.
|
||||
* Any `MapReduceOptions.extraOption` is silently ignored.
|
||||
* `WriteResult` does not longer hold error information but throws an Exception.
|
||||
* `MongoOperations.executeInSession(…)` no longer calls `requestStart` / `requestDone`.
|
||||
* Index name generation has become a driver internal operations, still we use the 2.x schema to generate names.
|
||||
* Some Exception messages differ between the generation 2 and 3 servers as well as between _MMap.v1_ and _WiredTiger_ storage engine.
|
||||
|
||||
* `WriteResult` no longer holds error information but, instead, throws an `Exception`.
|
||||
* `MongoOperations.executeInSession(…)` no longer calls `requestStart` and `requestDone`.
|
||||
* Index name generation has become a driver-internal operation. Spring Data MongoDB still uses the 2.x schema to generate names.
|
||||
* Some `Exception` messages differ between the generation 2 and 3 servers as well as between the MMap.v1 and WiredTiger storage engines.
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
[[mongo.auditing]]
|
||||
== General auditing configuration
|
||||
== General Auditing Configuration for MongoDB
|
||||
|
||||
Activating auditing functionality is just a matter of adding the Spring Data Mongo `auditing` namespace element to your configuration:
|
||||
To activate auditing functionality, add the Spring Data Mongo `auditing` namespace element to your configuration, as the following example shows:
|
||||
|
||||
.Activating auditing using XML configuration
|
||||
.Activating auditing by using XML configuration
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
@@ -11,7 +11,7 @@ Activating auditing functionality is just a matter of adding the Spring Data Mon
|
||||
----
|
||||
====
|
||||
|
||||
Since Spring Data MongoDB 1.4 auditing can be enabled by annotating a configuration class with the `@EnableMongoAuditing` annotation.
|
||||
Since Spring Data MongoDB 1.4, auditing can be enabled by annotating a configuration class with the `@EnableMongoAuditing` annotation, as the followign example shows:
|
||||
|
||||
.Activating auditing using JavaConfig
|
||||
====
|
||||
@@ -29,5 +29,4 @@ class Config {
|
||||
----
|
||||
====
|
||||
|
||||
If you expose a bean of type `AuditorAware` to the `ApplicationContext`, the auditing infrastructure will pick it up automatically and use 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`.
|
||||
|
||||
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`.
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
[[mongo.repositories]]
|
||||
= MongoDB repositories
|
||||
= MongoDB Repositories
|
||||
|
||||
[[mongo-repo-intro]]
|
||||
== Introduction
|
||||
|
||||
This chapter will point out the specialties for repository support for MongoDB. This builds on the core repository support explained in <<repositories>>. So make sure you've got 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 <<repositories>>. 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 leverage our sophisticated repository support that eases implementing those quite significantly. To do so, simply create an interface for your repository:
|
||||
To access domain entities stored in a MongoDBm, 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 +28,7 @@ public class Person {
|
||||
----
|
||||
====
|
||||
|
||||
We have a quite simple domain object here. Note that it has a property named `id` of type `ObjectId`. The default serialization mechanism used in `MongoTemplate` (which is backing the repository support) regards properties named id as 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 `ObjectId`. 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. Now that we have a domain object, we can define an interface that uses it, as follows:
|
||||
|
||||
.Basic repository interface to persist Person entities
|
||||
====
|
||||
@@ -41,7 +41,7 @@ public interface PersonRepository extends PagingAndSortingRepository<Person, Lon
|
||||
----
|
||||
====
|
||||
|
||||
Right now this interface simply serves typing purposes but we will add additional methods to it later. In your Spring configuration simply add
|
||||
Right now this interface serves only to provide type information, but we can add additional methods to it later. To do so, in your Spring configuration, add the following content:
|
||||
|
||||
.General MongoDB repository Spring configuration
|
||||
====
|
||||
@@ -69,11 +69,11 @@ Right now this interface simply serves typing purposes but we will add additiona
|
||||
----
|
||||
====
|
||||
|
||||
This namespace element will cause the base packages to be scanned for interfaces extending `MongoRepository` and create Spring beans for each of them found. By default the repositories will 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.
|
||||
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.
|
||||
|
||||
If you'd rather like to go with JavaConfig use the `@EnableMongoRepositories` annotation. The annotation carries the very same attributes like the namespace element. If no base package is configured the infrastructure will scan the package of the annotated configuration class.
|
||||
If you would rather go with Java-based configuration, 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:
|
||||
|
||||
.JavaConfig for repositories
|
||||
.Java configuration for repositories
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@@ -99,7 +99,7 @@ class ApplicationConfig extends AbstractMongoConfiguration {
|
||||
----
|
||||
====
|
||||
|
||||
As 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. So accessing the second page of `Person` s at a page size of 10 would simply look something like this:
|
||||
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:
|
||||
|
||||
.Paging access to Person entities
|
||||
====
|
||||
@@ -121,12 +121,12 @@ public class PersonRepositoryTests {
|
||||
----
|
||||
====
|
||||
|
||||
The sample creates an application context with Spring's unit test support which will perform annotation based dependency injection into test cases. Inside the test method we simply use the repository to query the datastore. We hand the repository a `PageRequest` instance that requests the first page of persons at a page size of 10.
|
||||
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.
|
||||
|
||||
[[mongodb.repositories.queries]]
|
||||
== Query methods
|
||||
== Query Methods
|
||||
|
||||
Most of the data access operations you usually trigger on a repository result a query being executed against the MongoDB databases. Defining such a query is just a matter of declaring a method on the repository interface
|
||||
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:
|
||||
|
||||
.PersonRepository with query methods
|
||||
====
|
||||
@@ -143,15 +143,18 @@ public interface PersonRepository extends PagingAndSortingRepository<Person, Str
|
||||
Stream<Person> findAllBy(); <4>
|
||||
}
|
||||
----
|
||||
<1> The method shows a query for all people with the given lastname. The query will be derived parsing the method name for constraints which can be concatenated with `And` and `Or`. Thus the method name will result in a query expression of `{"lastname" : lastname}`.
|
||||
<2> Applies pagination to a query. Just equip your method signature with a `Pageable` parameter and let the method return a `Page` instance and we will automatically page the query accordingly.
|
||||
<3> Shows that you can query based on properties which are not a primitive type.
|
||||
<4> Uses a Java 8 `Stream` which reads and converts individual elements while iterating the stream.
|
||||
<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.
|
||||
====
|
||||
|
||||
|
||||
|
||||
NOTE: Note that for version 1.0 we currently don't support referring to parameters that are mapped as `DBRef` in the domain class.
|
||||
NOTE: For version 1.0, we currently do not support referring to parameters that are mapped as `DBRef` in the domain class.
|
||||
|
||||
The following table shows the keywords that are supported for query methods:
|
||||
|
||||
[cols="1,2,3", options="header"]
|
||||
.Supported keywords for query methods
|
||||
@@ -274,9 +277,9 @@ NOTE: Note that for version 1.0 we currently don't support referring to paramete
|
||||
|===
|
||||
|
||||
[[mongodb.repositories.queries.delete]]
|
||||
=== Repository delete queries
|
||||
=== Repository Delete Queries
|
||||
|
||||
The above keywords can be used in conjunction with `delete…By` or `remove…By` to create queries deleting matching documents.
|
||||
The keywords in the preceding table can be used in conjunction with `delete…By` or `remove…By` to create queries that delete matching documents.
|
||||
|
||||
.`Delete…By` Query
|
||||
====
|
||||
@@ -291,12 +294,14 @@ public interface PersonRepository extends MongoRepository<Person, String> {
|
||||
----
|
||||
====
|
||||
|
||||
Using return type `List` will retrieve and return all matching documents before actually deleting them. A numeric return type directly removes the matching documents returning the total number of documents removed.
|
||||
Using a return type of `List` retrieves and returns all matching documents before actually deleting them. A numeric return type directly removes the matching documents, returning the total number of documents removed.
|
||||
|
||||
[[mongodb.repositories.queries.geo-spatial]]
|
||||
=== Geo-spatial repository queries
|
||||
=== Geo-spatial Repository Queries
|
||||
|
||||
As you've just seen there are a few keywords triggering geo-spatial operations within a MongoDB query. The `Near` keyword allows some further modification. Let's have a look at some examples:
|
||||
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:
|
||||
|
||||
.Advanced `Near` queries
|
||||
====
|
||||
@@ -310,7 +315,7 @@ public interface PersonRepository extends MongoRepository<Person, String>
|
||||
----
|
||||
====
|
||||
|
||||
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 will transparently use `$nearSphere` instead of $code.
|
||||
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`
|
||||
====
|
||||
@@ -323,11 +328,15 @@ Distance distance = new Distance(200, Metrics.KILOMETERS);
|
||||
----
|
||||
====
|
||||
|
||||
As you can see using a `Distance` equipped with a `Metric` causes `$nearSphere` clause to be added instead of a plain `$near`. 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: Using `@GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)` on the target property forces usage of `$nearSphere` operator.
|
||||
(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.)
|
||||
|
||||
==== Geo-near queries
|
||||
NOTE: Using `@GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)` on the target property forces usage of the `$nearSphere` operator.
|
||||
|
||||
==== Geo-near Queries
|
||||
|
||||
Spring Data MongoDb supports geo-near queries, as the following example shows:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -352,9 +361,9 @@ public interface PersonRepository extends MongoRepository<Person, String>
|
||||
----
|
||||
|
||||
[[mongodb.repositories.queries.json-based]]
|
||||
=== MongoDB JSON based query methods and field restriction
|
||||
=== MongoDB JSON-based Query Methods and Field Restriction
|
||||
|
||||
By adding the annotation `org.springframework.data.mongodb.repository.Query` repository finder methods you can specify a MongoDB JSON query string to use instead of having the query derived from the method name. For example
|
||||
By adding the `org.springframework.data.mongodb.repository.Query` annotation to your repository finder methods, you can specify a MongoDB JSON query string to use instead of having the query be derived from the method name, as the following example shows:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -366,11 +375,11 @@ public interface PersonRepository extends MongoRepository<Person, String>
|
||||
}
|
||||
----
|
||||
|
||||
The placeholder `?0` lets you substitute the value from the method arguments into the JSON query string.
|
||||
The `?0` placeholder lets you substitute the value from the method arguments into the JSON query string.
|
||||
|
||||
NOTE: `String` parameter values are escaped during the binding process, which means that it is not possible to add MongoDB specific operators via the argument.
|
||||
NOTE: `String` parameter values are escaped during the binding process, which means that it is not possible to add MongoDB specific operators through the argument.
|
||||
|
||||
You can also use the filter property to restrict the set of properties that will be mapped into the Java object. For example,
|
||||
You can also use the filter property to restrict the set of properties that is mapped into the Java object, as the following example shows:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -382,16 +391,16 @@ public interface PersonRepository extends MongoRepository<Person, String>
|
||||
}
|
||||
----
|
||||
|
||||
This will return only the firstname, lastname and Id properties of the Person objects. The age property, a java.lang.Integer, will not be set and its value will therefore be 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.json-spel]]
|
||||
=== JSON based queries with SpEL expressions
|
||||
=== JSON-based Queries with SpEL Expressions
|
||||
|
||||
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 arguments. The the following query uses `[0]`
|
||||
to declare the predicate value for `lastname` that is equivalent to the `?0` parameter binding.
|
||||
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]
|
||||
----
|
||||
@@ -402,8 +411,8 @@ public interface PersonRepository extends MongoRepository<Person, String>
|
||||
}
|
||||
----
|
||||
|
||||
Expressions can be used to invoke functions, evaluate conditionals and construct values. SpEL expressions
|
||||
reveal in conjunction with JSON a side-effect as Map-like declarations inside of SpEL read like JSON.
|
||||
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]
|
||||
----
|
||||
@@ -414,12 +423,12 @@ public interface PersonRepository extends MongoRepository<Person, String>
|
||||
}
|
||||
----
|
||||
|
||||
SpEL in query strings can be a powerful way to enhance queries and can accept a broad range of unwanted arguments.
|
||||
You should make sure to sanitize strings before passing these to the query to avoid unwanted changes to your query.
|
||||
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`
|
||||
than can contribute properties, functions and customize the root object. Extensions are retrieved from the application context
|
||||
at the time of SpEL evaluation when the query is build.
|
||||
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`:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -441,19 +450,19 @@ NOTE: Bootstrapping `MongoRepositoryFactory` yourself is not application context
|
||||
to pick up Query SPI extensions.
|
||||
|
||||
[[mongodb.repositories.queries.type-safe]]
|
||||
=== Type-safe Query methods
|
||||
=== Type-safe Query Methods
|
||||
|
||||
MongoDB repository support integrates with the http://www.querydsl.com/[QueryDSL] project which provides a means to perform type-safe queries in Java. To quote from the project description, "Instead of writing queries as inline strings or externalizing them into XML files they are constructed via a fluent API." It provides the following features
|
||||
MongoDB repository support integrates with the http://www.querydsl.com/[QueryDSL] project, which provides a way to perform type-safe queries. To quote from the project description, "Instead of writing queries as inline strings or externalizing them into XML files they are constructed via a fluent API." It provides the following features:
|
||||
|
||||
* Code completion in IDE (all properties, methods and operations can be expanded in your favorite Java IDE)
|
||||
* Almost no syntactically invalid queries allowed (type-safe on all levels)
|
||||
* Domain types and properties can be referenced safely (no Strings involved!)
|
||||
* Adopts better to refactoring changes in domain types
|
||||
* Incremental query definition is easier
|
||||
* Code completion in the IDE (all properties, methods, and operations can be expanded in your favorite Java IDE).
|
||||
* Almost no syntactically invalid queries allowed (type-safe on all levels).
|
||||
* Domain types and properties can be referenced safely -- no strings involved!
|
||||
* Adapts better to refactoring changes in domain types.
|
||||
* Incremental query definition is easier.
|
||||
|
||||
Please refer to the http://www.querydsl.com/static/querydsl/latest/reference/html/[QueryDSL documentation] which describes how to bootstrap your environment for APT based code generation using Maven or Ant.
|
||||
See the http://www.querydsl.com/static/querydsl/latest/reference/html/[QueryDSL documentation] for how to bootstrap your environment for APT-based code generation using Maven or Ant.
|
||||
|
||||
Using QueryDSL you will be able to write queries as shown below
|
||||
QueryDSL lets you write queries such as the following:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -464,9 +473,9 @@ Page<Person> page = repository.findAll(person.lastname.contains("a"),
|
||||
new PageRequest(0, 2, Direction.ASC, "lastname"));
|
||||
----
|
||||
|
||||
`QPerson` is a class that is generated (via the Java annotation post processing tool) which is a `Predicate` that allows you to write type safe queries. Notice that there are no strings in the query other than the value "C0123".
|
||||
`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 via the interface `QueryDslPredicateExecutor` which is shown below
|
||||
You can use the generated `Predicate` class by using the `QueryDslPredicateExecutor` interface, which the following listing shows:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -484,7 +493,7 @@ public interface QueryDslPredicateExecutor<T> {
|
||||
}
|
||||
----
|
||||
|
||||
To use this in your repository implementation, simply inherit from it in addition to other repository interfaces. This is shown below
|
||||
To use this in your repository implementation, add it to the list of repository interfaces from which your interface inherits, as the following example shows:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -494,13 +503,12 @@ public interface PersonRepository extends MongoRepository<Person, String>, Query
|
||||
}
|
||||
----
|
||||
|
||||
We think you will find this an extremely powerful tool for writing MongoDB queries.
|
||||
|
||||
[[mongodb.repositories.queries.full-text]]
|
||||
=== Full-text search queries
|
||||
MongoDBs full text search feature is very store specific and therefore can rather be found on `MongoRepository` than on the more general `CrudRepository`. What we need is a document with a full-text index defined for (Please see section <<mapping-usage-indexes.text-index>> for creating).
|
||||
=== Full-text Search Queries
|
||||
|
||||
Additional methods on `MongoRepository` take `TextCriteria` as input parameter. In addition to those explicit methods, it is also possible to add a `TextCriteria` derived repository method. The criteria will be added as an additional `AND` criteria. Once the entity contains a `@TextScore` annotated property the documents full-text score will be retrieved. Furthermore the `@TextScore` annotated property will also make it possible to sort by the documents score.
|
||||
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).
|
||||
|
||||
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]
|
||||
----
|
||||
@@ -537,13 +545,10 @@ List<FullTextDocument> result = repository.findByTitleOrderByScoreDesc("mongodb"
|
||||
|
||||
include::../{spring-data-commons-docs}/repository-projections.adoc[leveloffset=+2]
|
||||
|
||||
[[mongodb.repositories.misc]]
|
||||
== Miscellaneous
|
||||
|
||||
[[mongodb.repositories.misc.cdi-integration]]
|
||||
=== CDI Integration
|
||||
== CDI Integration
|
||||
|
||||
Instances of the repository interfaces are usually created by a container, which 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 allows using the repository abstraction in CDI environments. The extension is part of the JAR so all you need to do to activate it is dropping the Spring Data MongoDB JAR into your classpath. You can now set up the infrastructure by implementing a CDI Producer for the `MongoTemplate`:
|
||||
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]
|
||||
----
|
||||
@@ -559,7 +564,7 @@ class MongoTemplateProducer {
|
||||
}
|
||||
----
|
||||
|
||||
The Spring Data MongoDB CDI extension will pick up the `MongoTemplate` available as CDI bean and create 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:
|
||||
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]
|
||||
----
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,9 @@
|
||||
[[query-by-example.execution]]
|
||||
== Executing an example
|
||||
== Running an Example
|
||||
|
||||
.Query by Example using a Repository
|
||||
The following example shows how to query by example when using a repository (of `Person` objects, in this case):
|
||||
|
||||
.Query by Example using a repository
|
||||
====
|
||||
[source, java]
|
||||
----
|
||||
@@ -20,9 +22,9 @@ public class PersonService {
|
||||
----
|
||||
====
|
||||
|
||||
An `Example` containing an untyped `ExampleSpec` uses the Repository type and its collection name. Typed `ExampleSpec` use their type as result type and the collection name from the Repository.
|
||||
An `Example` containing an untyped `ExampleSpec` uses the Repository type and its collection name. Typed `ExampleSpec` instances use their type as the result type and the collection name from the `Repository` instance.
|
||||
|
||||
NOTE: When including `null` values in the `ExampleSpec` Spring Data Mongo uses embedded document matching instead of dot notation property matching. This forces exact document matching for all property values and the property order in the embedded document.
|
||||
NOTE: When including `null` values in the `ExampleSpec`, Spring Data Mongo uses embedded document matching instead of dot notation property matching. Doing so forces exact document matching for all property values and the property order in the embedded document.
|
||||
|
||||
Spring Data MongoDB provides support for the following matching options:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user