简体   繁体   中英

How add pagination on Criteria api using typedQuery?

I am using Criteria API with pageable to return a Page<MyClass> with pageable, but when I insert setFirstResult and setMaxResults the query always returns 10 elements.

If I remove setFirstResult and setMaxResults from TypedQuery, my typedQuery.getResultList() returns all elements but obviously without pagination.

I have a service that calls my criteria sending my pageable for the main function peopleRepository.filter

public Page<People> filtrarParcial(String name, String rg, String mom, String cpf, String nickname, Integer pageNumber, Integer pageSize, List<String> sort) {
    List<Sort.Order> orders = new ArrayList<>();

    PageRequest pageRequest = PageRequest.of(pageNumber, pageSize, Sort.by(orders));

    Page<People> listPeople = peopleRepository.filter(name, rg, mom, cpf, nickname, pageRequest);

    return listPeople;
}

My repository implements

@Service
public class PeopleRepositoryImpl implements PeopleRepositoryQueries {
    @PersistenceContext
    private EntityManager manager;

    @Transactional(readOnly = true)
    public Page<People> filter(String name, String rg, String mom, String cpf, String nickname, Pageable pageable) {

        CriteriaBuilder criteriaBuilder = manager.getCriteriaBuilder();
        CriteriaQuery<People> query = criteriaBuilder.createQuery(People.class);

        Root<People> root = query.from(People.class);

        Path<String> nomePath = root.<String>get("name");

        List<Predicate> predicates = new ArrayList<Predicate>();

        if(!nome.equals("")) {
            Predicate nomeIgual = criteriaBuilder.like(nomePath, "%" +name.toUpperCase() + "%");
            predicates.add(nomeIgual);
        }

        query.where((Predicate[]) predicates.toArray(new Predicate[0]));

        int paginaAtual = pageable.getPageNumber();
        int totalRegistrosPorPagina = pageable.getPageSize();
        int primeiroRegistro = paginaAtual * totalRegistrosPorPagina;

        TypedQuery<People> typedQuery = manager.createQuery(query);

//      typedQuery.setFirstResult(primeiroRegistro);
//      typedQuery.setMaxResults(totalRegistrosPorPagina);

        Integer totalRows = typedQuery.getResultList().size();

        Long total = totalRows.longValue();
        return new PageImpl<>(typedQuery.getResultList(), pageable, total);
    }

If I search for example a people with name marcos , typedQuery.getResultList() returns only 10 elements coincidentally with the same number elements by page (in my database there are 180). If I remove this

typedQuery.setFirstResult(primeiroRegistro);
typedQuery.setMaxResults(totalRegistrosPorPagina);

then typedQuery.getResultList() returns 180 elements but with pagination, and all 180 elements are within single page without pagination

try with the below configurations.

CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
Root<People> entity_ = countQuery.from(query.getResultType());
entity_.alias("entitySub"); //use the same alias in order to match the restrictions part and the selection part
countQuery.select(criteriaBuilder.count(entity_));
Predicate restriction = query.getRestriction();
if (restriction != null) {
    countQuery.where(restriction); // Copy restrictions
}
Long totalCount=entityManager.createQuery(countQuery).getSingleResult();


query.setFirstResult(pageable.getOffset());
query.setMaxResults(pageable.getPageSize());
List<People> result = query.getResultList();
return PageableExecutionUtils.getPage(result,pageable, () -> totalCount);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM