Search code examples
springspring-data-jpaquerydsl

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?


Solution

  • It should work like this if you can't find another way

    private Sort sortBy(Path<?> path) {
        return new Sort(Sort.Direction.ASC, path.getMetadata().getExpression().toString());
    }