Add Querydsl support
Tip submitted by @omrzljak
In some cases spring-data query possibilities are not enough to make your queries. You can use @Query annotation and write your own. Some of us like to write type safe queries like Querydsl provides.
Generated Predicate classes
An important part of Querydsl are generated domain classes for queries so called Predicate. In case of spring-data-mongodb these are generated by the Java annotation post processing tool.
Gradle plugin
There is also Gradle plugin for Querydsl which supports configuration for spring-data-mongodb.
Maven
There is also plugin for maven. But in this tip
we describe only gradle
configuration.
Changes
build.gradle
Add the Querydsl plugin
configuration grunt.initConfig
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "com.ewerk.gradle.plugins:querydsl-plugin:1.0.3"
}
}
apply plugin: "com.ewerk.gradle.plugins.querydsl"
querydsl {
// we use mongodb
springDataMongo = true
}
compile "com.mysema.querydsl:querydsl-mongodb:3.6.0"
Note we use MongoDB but Querydsl plugin supports also more options.
If you run gradle build
you will see output like this
Note: Generating net.jogat.names.domain.QName for [net.jogat.names.domain.Name]
For every domain class which is annotated with @Document Querydsl plugin will generate one Predicate class.
Change Repository classes
If you have a domain class for example Name
, then you have also a NameRepository
class. You have to change every Repository class to extend from QuerydslPredicateExecutor
.
public interface NameRepository extends MongoRepository<Name, String>, QuerydslPredicateExecutor<Name> {
This will extend your repository class with extra methods supporting Querydsl (see )
Write type safe queries
Gradle plugin has generated class QName which can be used for writing queries for Name.class. Here is Java example:
QName name = new QName("name");
// count all names whose list "categorie" contains string "TOP_EVER"
nameRepository.count(name.categories.contains("TOP_EVER"));