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

beginner_ picture beginner_ · Oct 25, 2012 · Viewed 20.2k times · Source

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.

Answer

Frank picture Frank · Oct 27, 2012

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())));
    }
}