添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

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:


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.


Right now this interface simply serves typing purposes but we will add additional methods to it later. In your Spring configuration simply add


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.

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.


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:


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.

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


The first 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} . The second example shows how pagination is applied 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. The third examples shows that you can query based on properties which are not a primitive type.

[Note] Note

Note that for version 1.0 we currently don't support referring to parameters that are mapped as DBRef in the domain class.


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 look at some examples:


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.


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.

MongoDB repository support integrates with the 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

  • 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

Please refer to the QueryDSL documentation which describes how to bootstrap your environment for APT based code generation using Maven or using Ant .

Using QueryDSL you will be able to write queries as shown below

QPerson person = new QPerson("person");
List<Person> result = repository.findAll(person.address.zipCode.eq("C0123"));
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".

You can use the generated Predicate class via the interface QueryDslPredicateExecutor which is shown below

public interface QueryDslPredicateExecutor<T> {
  T findOne(Predicate predicate);
  List<T> findAll(Predicate predicate);
  List<T> findAll(Predicate predicate, OrderSpecifier<?>... orders);
  Page<T> findAll(Predicate predicate, Pageable pageable);
  Long count(Predicate predicate);

To use this in your repository implementation, simply inherit from it in additiion to other repository interfaces. This is shown below

public interface PersonRepository extends MongoRepository<Person, String>, QueryDslPredicateExecutor<Person> {