Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a paged QueryDSL query with Spring JPA?

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 OrderSpecifiers 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.Orders which are a lot like OrderSpecifiers, 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?

like image 651
eh. Avatar asked Jul 26 '12 15:07

eh.


People also ask

How can I apply pagination in JPA?

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.

What is Querydsl JPA?

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.

Which is better CrudRepository or JpaRepository?

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.


2 Answers

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...

like image 171
Michael Wiles Avatar answered Nov 01 '22 10:11

Michael Wiles


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()))
like image 43
SergeyB Avatar answered Nov 01 '22 09:11

SergeyB