JPA CriteriaQuery implements Spring Data Pageable.getSort()

Javatar picture Javatar · Jan 17, 2017 · Viewed 18.1k times · Source

I used JPA CriteriaQuery to build my dynamic Query and pass in a Spring Data Pageable object:

sort=name,desc

At the backend I have a method in my Repository to support dynamic query:

public Page<User> findByCriteria(String username, Pageable page) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<User> cq = cb.createQuery(User.class);
    Root<User> iRoot = cq.from(User.class);
    List<Predicate> predicates = new ArrayList<Predicate>();

    if (StringUtils.isNotEmpty(username)) {
        predicates.add(cb.like(cb.lower(iRoot.<String>get("username")), "%" + username.toLowerCase() + "%"));
    }

    Predicate[] predArray = new Predicate[predicates.size()];
    predicates.toArray(predArray);

    cq.where(predArray);

    TypedQuery<User> query = em.createQuery(cq);

    int totalRows = query.getResultList().size();

    query.setFirstResult(page.getPageNumber() * page.getPageSize());
    query.setMaxResults(page.getPageSize());

    Page<User> result = new PageImpl<User>(query.getResultList(), page, totalRows);

    return result;
}

Note: I put only one param for demo purpose.

However the returned data is unsorted therefore I would like to ask is that any way to implement Pageable in CriteriaQuery.

Answer

Konrad Początek picture Konrad Początek · May 20, 2020

You can add sorting using QueryUtils from spring: query.orderBy(QueryUtils.toOrders(pageable.getSort(), root, builder));