如何使用typedQuery在Criteria api上添加分页?

时间:2019-05-10 11:55:37

标签: java spring spring-boot hibernate-criteria criteria-api

我正在使用带有pageable的Criteria API返回具有pageable的Page,但是当我插入'setfirstresult'和setmaxresults时,查询总是返回10个元素。

如果我从TypedQuery中删除setFirstResult和setMaxResults,则我的typedQuery.getResulList()返回所有元素,但显然没有分页。

我有一项服务,该服务调用我的条件,将主要功能“ 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;
    }

我的存储库实现

@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);
    }

例如,如果我搜索一个具有marcos名称的人,则typedQuery.getResultList()仅按页同时返回10个元素和相同数量的元素(在我的数据库中为180个)。如果我删除此

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

我的typedQuery.getResultList()返回180个元素,但具有分页功能,一个页面中的所有180个元素都没有分页

1 个答案:

答案 0 :(得分:0)

尝试以下配置。

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);