Add Querydsl support

Tip submitted by @omrzljak, updated by @arnaud-deprez

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 plugin

There is also a plugin for Maven. Maven configuration is fully described in the chapter Maven integration of the documentation. You also need to perform the steps below.

Note: Do not include the org.slf4j dependency because it is included in Spring Boot.

Changes

build.gradle

In build.gradle, add the dependency to Querydsl plugin

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "gradle.plugin.com.ewerk.gradle.plugins:querydsl-plugin:1.0.9"
    }
}

apply from: 'gradle/querydsl.gradle'

Define the Querydsl version to use in your gradle.properties

querydsl_version=4.1.4

Then create a the file gradle/querydsl.gradle with

apply plugin: "com.ewerk.gradle.plugins.querydsl"

sourceSets {
    main {
        java {
            srcDir "$buildDir/generated/source/apt/main"
        }
    }
}

querydsl {
    // we use mongodb
    springDataMongo = true
    querydslSourcesDir = "$buildDir/generated/source/apt/main"
}

dependencies {
    compile "com.querydsl:querydsl-mongodb:${querydsl_version}"
    compileOnly "com.querydsl:querydsl-apt:${querydsl_version}"
}

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 )

Web support

To extend the rest controller for support parameterized request, you have to add com.mysema.query.types.Predicate annotated with org.springframework.data.querydsl.binding.QuerydslPredicate to the method parameters:

@RestController
@RequestMapping("/api")
class NameResource {

    private final NameRepository nameRepository;
    
    public NameResource(NameRepository nameRepository) {
        this.nameRepository = nameRepository;
    }

    @RequestMapping(value = "/names",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<List<Name>> getAllNames(@QuerydslPredicate(root = Name.class) Predicate predicate,
                                                    Pageable pageable) {
        log.debug("REST request to get a page of Name");
        Page<Name> page = nameRepository.findAll(predicate, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/names");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }
    ...
}

Also in NameResourceIntTest you have to support QuerydslPredicateArgumentResolver:

public class NameResourceIntTest {
    ...
    @Autowired
    private NameRepository nameRepository;
    @Autowired
    private QuerydslPredicateArgumentResolver querydslPredicateArgumentResolver;

    @PostConstruct
    public void setup() {
        MockitoAnnotations.initMocks(this);
        NameResource nameResource = new nameResource(nameRepository);
        this.restNameMockMvc = MockMvcBuilders.standaloneSetup(nameResource)
            .setCustomArgumentResolvers(pageableArgumentResolver, querydslPredicateArgumentResolver)
            .setMessageConverters(jacksonMessageConverter).build();
    }
    ...
}

More details can be found in the documentation.

Write type safe queries

Gradle or maven plugins have generated class QName which can be used for writing queries for Name.class. Here is Java example:

QName name = QName.name;

// count all names whose list "categorie" contains string "TOP_EVER"
nameRepository.count(name.categories.contains("TOP_EVER"));