Querydsl is a framework which supports writing type safe queries with back-end services like JPA, MongoDB, SQL and etc.

Rather than constructing queries with String or XML, we can leverage Querydsl’s fluent API for the type safety.
I faced few difficulties in configuring Querydsl in Gradle. Querydsl needs generated model classes from the Hibernate model classes.

However, to do this job, a plugin is required. For Maven that plugin is maintained by Mysema,which also maintains Querydsl. This is the link for Gradle plugin developed by ewerk(I found the website broken).  Some tweaks are needed to make this plugin work with Gradle 5 and onwards.
The following is a build.gradle file – 


apply plugin: 'com.ewerk.gradle.plugins.querydsl'
def queryDslSourceDirectory = 'src/main/generated'

querydsl {
    jpa = true
    querydslSourcesDir = queryDslSourceDirectory

sourceSets {
    main {
        java {
            srcDir queryDslSourceDirectory

compileQuerydsl {
    options.annotationProcessorPath = configurations.querydsl

configurations {
    querydsl.extendsFrom compileClasspath

test {

If we run the gradle clean build command, Querydsl model files will be generated in src/main/generated folder. One class will be generated for every Hibernate model class, prefixed with ‘Q’.
This is User.java, the entity class –

public class User extends AbstractAuditingEntity {
    private String name;
    private String password;
    private String email;
    private String phone;
    private Date dateOfBirth;
    private String avatar;
    private Gender gender;
    private Role role;
    private Status status;
    public enum Gender {MALE, FEMALE}
    public enum Role {USER, ADMIN}
    public enum Status {PENDING, ACTIVE, INACTIVE}


In this method we are executing a SELECT query on User entity –

public List<User> findUsersWithNamePart(String namePart) {
    return jpaQueryFactory.selectFrom(user)

In this project a custom Interface is used (UserRespositoryCustom.java) for Querydsl methods. The idea is to keep all Querydsl queries in the Repository layer and keep Service layer out of it.
There is a test method in SpringBootQueryDslApplicationTests.java

public void queryDslTest() {
    User user = User.newObjectWithDefaults();

    List<User> users = userRepository.findUsersWithNamePart("onn");

    assertThat(users.size(), greaterThan(0));
    assertThat(users.get(0).getEmail(), is("ronnie@email.com"));

This is the project URL – https://github.com/ronniegnr/poc-project/tree/master/spring-boot-querydsl
Check this for more information on Querydsl query api – http://blog.mysema.com/2010/07/querying-hibernate-with-querydsl.html

Previous ArticleNext Article

Leave a Reply

Your email address will not be published. Required fields are marked *