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

别来无恙 提交于 2019-12-20 12:16:11

问题


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.


回答1:


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 orderByExpression = new PathBuilder(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())));
                }
            }




回答2:


I don't know if it is still relevant but there is an implementation in the spring data jpa for doing the conversion between a data.domain.Sort (Spring JPA) Object to an OrderSpecifier (QueryDSL).

GIT Source of Querydsl Support in Spring JPA

It is really ugly implementation but you could still reuse it for your own purpose as the method is private:

public JPQLQuery applySorting(Sort sort, JPQLQuery query)

But if you use Spring data JPA, in your custom Repository implementation, you just need to do:

public Page<MyObject> findAll(Predicate predicate, Pageable pageable) {

    QMyObject myObject = QMyObject.myObject;
    JPQLQuery jPQLQuery = from(myObject)
            .join(myObject.user)
            .where(predicate);
    jPQLQuery = getQuerydsl().applyPagination(pageable, jPQLQuery);
    List<MyObject> myObjectList = jPQLQuery.list(myObject);
    long count =  jPQLQuery.count();
    Page<MyObject> myObjectPage = new PageImpl<MyObject>(myObjectList, pageable, count);
    return myObjectPage;  
}

Hope it could help!




回答3:


org.springframework.data.domain.Sort.Order and com.querydsl.core.types.Order and are so similar, yet there is no straightforward conversion between the two. This is somewhat improved version of frozenfury answer:

PathBuilder<Entity> entityPath = new PathBuilder<>(Entity.class, "entity");
for (Order order : pageable.getSort()) {
    PathBuilder<Object> path = entityPath.get(order.getProperty());
    query.orderBy(new OrderSpecifier(com.querydsl.core.types.Order.valueOf(order.getDirection().name()), path));
}


来源:https://stackoverflow.com/questions/13072378/how-can-i-convert-a-spring-data-sort-to-a-querydsl-orderspecifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!