Dynamic SQL Querying & Pagination with Querydsl and Spring Data JPA

Last Updated:  June 18, 2020 | Published: December 5, 2018

Returning all the data in a table within a REST call can be slow if your table grows. Imagine a simple HTML <table></table> to show all the registered persons in your database. Even if you could return the whole dataset within one HTTP request, the user wouldn't be able to read them all at once as he has to scroll down. In addition, the user sometimes wants to filter the dataset to return only a part of the entire table. Writing code to fulfill these requirements (pagination & dynamic querying) from scratch can be quite cumbersome. Luckily Spring Data provides different approaches to address this and is easy-to-use. In this blog post, I'll show you how to do dynamic SQL querying with paginated data with Querydsl and Spring Data JPA for a simple REST endpoint.

Project setup for Querydsl with Spring Data JPA

Starting with the pom.xml , I've bootstrapped a simple Spring Boot application and added the dependency for Querydsl (the version is managed by Spring Boot and you don't have to specify it explicitly):

Pagination is already built-in Spring Data as you can pass an instance of PageRequest to the query methods of your JpaRepository and specify the page number, page size, and sorting with this object. To achieve dynamic SQL queries, there are several approaches within Spring Data as you can use JPA's Criteria API, use query by example, and the Querydsl integration support (for more information, have a look at the Spring Data documentation). I've tried all of them and picked Querydsl as it covered most of my use cases. Furthermore, it is easy to integrate and use.

Using Querydsl you need to update your build section within your pom.xml :

The apt-maven-plugin will generate Querydsl specific source code out of your JPA entities for you. These generated classes are required to query the database as you will see later on. If you have trouble and can't use the generated classes, make sure the project builds automatically. Check this within your IDE or update the Maven project (ALT + F5 within Eclipse).

JPA and Querydsl entity setup

For this quick demo, I am using the following JPA entity:

To populate some random data to effectively use pagination and dynamic queries, I am adding 10.000 persons to the in-memory H2 database during the application startup:

Endpoint to filter and paginate data with Querydsl and Spring Data JPA

Within the HTTP request, I want to be able to specify the page number, the page size, and filter the data by searching for exact matches of some attributes.

The REST controller for this looks like the following:

I've added several @RequestParam to the endpoint to be able to filter the dataset. For demo purposes, the code is part of the controller class. You can (and maybe should) also easily extract it to a service class. The first thing you may notice is the usage of the class QPerson for building the requested SQL statements. This class is generated by the apt-maven-plugin and Querydsl will add the letter in front of all your JPA entities. With this class, you have access to the entity's attributes and specify typesafe filters. The BooleanBuilder is used to concatenate the filter criteria via SQL's AND operator.

If your queried domain object is quite bigger then this example and if you want to reduce the if statements, you can use Spring Data's Querydsl predicate-argument resolving within a controller method. The default behavior uses eq for binding simple properties of your domain object. For detailed documentation and further configuration, have a look at the following links: Spring Data Querydsl Web Support and this running example on GitHub (thanks to @odrotbohm for this hint)

In this example, I am directly returning the Page<T> object as this contains important meta-data about the dataset for the frontend (for e.g. displaying paging buttons and min/max page indicators in your table) but you could also get only the data by calling .getContent() to return the list of objects.

To be able to pass the BooleanBuilder object to the .findAll() method of your repository, your interface has to extend the interface QuerydslPredicateExecutor<Person>:

Accessing the endpoint

You can now access the endpoint within your browser or REST client and play around with the filter e.g. http://localhost:8080/persons?firstname=Max&page=0&size=2 will result in:

The result object contains not only the requested persons but also the meta-data I already mentioned. With this data, your client is able to get the amount of totalPages and totalElements and can easily navigate further.

Some other possible requests might be:

A running example can be found in my GitHub repository. Therefore have a look at the README.md and follow the instructions.

Further resources on Querydsl and Spring Data JPA

Find further persistence related tips & tricks here:

Have fun with paging your data using Querydsl and Spring Data JPA,

Phil

    • Thank you for the comment Ollie,

      this will reduce my small “if-hell”. I’ll add a section for this simplified solution.

      PS: You are doing great work with your Spring Data team!

      Kind regards,
      Philip

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

    Sign up for Our Mailing List And Get

    the Testing Java Applications ($9) Cheat Sheet for Free

    Testing Java Applications Cheat Sheet Cover
    >