Andrea Bevilacqua
Andrea Bevilacqua

Reputation: 1357

Transform from Pageable.getSort() to List<Order> to sort a query made by Criteria API in a Spring repository custom

I've implemented one my custom Spring repository which receives in input a org.springframework.data.domain.Pageable object. This Pageable object has the following sort property (for example): id: DESC,name: ASC.

I need to convert the pageable.getSort() property into a List<Order> in order to set an order for the criteriaQuery.orderBy(List<Order>) method.

In order to retrieve a paged result, I used the new PageImpl passing it the pageable object, but this not manage the ordering.

TypedQuery<Entity> typedQuery = entityManager.createQuery(criteriaQuery);
typedQuery.setFirstResult(pageable.getOffset());
typedQuery.setMaxResults(pageable.getPageSize());
Page<Entity> page = new PageImpl<Entity>(typedQuery.getResultList(), pageable, typedQuery.getMaxResults());
return page;

Any suggests? Thanks, Andrea

Upvotes: 8

Views: 6217

Answers (1)

Vipin CP
Vipin CP

Reputation: 3807

It can be done using queryUtils.

 import org.springframework.data.jpa.repository.query.QueryUtils;
    criteriaQuery.orderBy(QueryUtils.toOrders(pageable.getSort(), rootEntity, criteriaBuilder));

Upvotes: 23

Related Questions