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> {