我使用带可分页的条件API返回带有可分页的Page<MyClass>,但是当我插入setFirstResult和setMaxResults时,查询总是返回10个元素。
如果将setFirstResult和setMaxResults从TypedQuery中删除,则typedQuery.getResultList()将返回所有元素,但显然没有分页。
我有一个服务,它调用我的条件,为主函数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个元素都在不分页的单个页面中。
发布于 2019-10-29 11:39:53
尝试使用以下配置。
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);https://stackoverflow.com/questions/56077215
复制相似问题