QueryDSL defines an OrderSpecifier
interface and an instance for that can be easily obtained for any field by calling asc()
or desc()
. The QueryDslPredicateExecutor
interface of Spring Data JPA even has a findAll()
method which takes OrderSpecifier
s as parameters.
org.springframework.data.domain.PageRequest
however doesn't know anything about QueryDSL and it has its own way for defining query sort order, namely org.springframework.data.domain.Sort
. It can contain a number of org.springframework.data.domain.Sort.Order
s which are a lot like OrderSpecifier
s, except that they are not type safe etc.
So, if I want to make paged query which uses sorting, is there really no way of using QueryDSL for defining that?
The simplest way to implement pagination is to use the Java Query Language – create a query and configure it via setMaxResults and setFirstResult: Query query = entityManager. createQuery("From Foo"); int pageNumber = 1; int pageSize = 10; query.
Querydsl is an extensive Java framework, which allows for the generation of type-safe queries in a syntax similar to SQL. It currently has a wide range of support for various backends through the use of separate modules including JPA, JDO, SQL, Java collections, RDF, Lucene, Hibernate Search, and MongoDB.
Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
I know it's been a while and I'm not sure this was available at the time of the OP but there is now a QPageRequest object introduced which allows for sorting via QueryDSL to be added to spring data jpa Query DSL...
Here is a much simpler way to construct a Sort
object using QueryDSL:
new QSort(user.manager.firstname.asc())
Then you can use it in a PageRequest
like so:
new PageRequest(0, 10, new QSort(user.manager.firstname.asc()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With