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

前端 未结 4 763
有刺的猬
有刺的猬 2021-02-04 06:23

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.

4条回答
  •  梦如初夏
    2021-02-04 07:21

    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 findAll(Predicate predicate, Pageable pageable) {
    
        QMyObject myObject = QMyObject.myObject;
        JPQLQuery jPQLQuery = from(myObject)
                .join(myObject.user)
                .where(predicate);
        jPQLQuery = getQuerydsl().applyPagination(pageable, jPQLQuery);
        List myObjectList = jPQLQuery.list(myObject);
        long count =  jPQLQuery.count();
        Page myObjectPage = new PageImpl(myObjectList, pageable, count);
        return myObjectPage;  
    }
    

    Hope it could help!

提交回复
热议问题