Is there something like JPA Specifications for Spring Data MongoDB Repositories?
If not, how can I make dynamic queries with repositories?
I found myself a way.
The trick can be done using QueryDSL, in the following way:
First, add the QueryDSL dependencies:
com.mysema.querydsl
querydsl-mongodb
${querydsl-mongo.version}
com.mysema.querydsl
querydsl-apt
${querydsl-mongo.version}
Then, configure the plugin in order to create Metamodels classes (their names will be the same of the documents with the letter Q as prefix: eg. QUser):
....
com.mysema.maven
apt-maven-plugin
1.1.3
process
target/generated-sources/java
org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor
Note the processor class: it's not the QueryDSL default one com.mysema.query.apt.morphia.MorphiaAnnotationProcessor, but the Spring Data MongoDB one org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor:
Spring Data Mongo provides a custom APT processor to generate the Metamodels instead of the one provided in QueryDSL, it will scan the Spring specific @Document instead of the Morphia specific annotations.
Now we can make our repository interface extending QueryDslPredicateExecutor:
public interface UserRepository extends MongoRepository, QueryDslPredicateExecutor,
QuerydslBinderCustomizer {
}
We can now define Predicates when querying the repository:
QUser user = QUser.user;
BooleanExpression predicate = user.name.containsIgnoreCase("John");
userRepository.findAll(predicate);
QuerydslBinderCustomizer helps you to define the binding of the Document's properties (see Spring documentation for further help).