Search code examples
spring-dataquerydsl

How can I convert a spring data Sort to a querydsl OrderSpecifier?


This is basically the opposite of this: How to do a paged QueryDSL query with Spring JPA?

This is for a custom query for which i can't use any of the findAll() methods.

EDIT:

Posted the wrong link. Now corrected.


Solution

  • You can do somethings like this: But make sure to trim the o.getProperty() so you only pass the property and not "alias."+property

    if (pageable != null) {
        query.offset(pageable.getOffset());
        query.limit(pageable.getPageSize());
        for (Sort.Order o : pageable.getSort()) {
            PathBuilder<Object> orderByExpression = new PathBuilder<Object>(Object.class, "object");
    
            query.orderBy(new OrderSpecifier(o.isAscending() ? com.mysema.query.types.Order.ASC
                    : com.mysema.query.types.Order.DESC, orderByExpression.get(o.getProperty())));
        }
    }