嗨,大家好,我正在尝试使用标准和分页,但是我的代码无法正常工作,这里是:
public Page<Person> getAuthorizationsTest() {
PageRequest pageRequest = new PageRequest(1, 5);
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Person> queryBase = criteriaBuilder.createQuery(Person.class);
Root<Person> root = queryBase.from(Person.class);
List<Predicate> queryConditions = new ArrayList<>();
Predicate predicate = criteriaBuilder.like(root.get("name"), "%[myValue]%");
queryConditions.add(predicate);
queryBase.where(queryConditions.toArray(new Predicate[]{}));
TypedQuery<Person> query = em.createQuery(queryBase);
List<Person> list = query.getResultList();
Page<Person> authorizations = new PageImpl<Person>(list, pageRequest, list.size());
return authorizations;
}
一切似乎都很好,但是当我执行它时,我收到一个列表页面,其中包含所有结果,而不仅是我的pageRequest中指定的结果
我究竟做错了什么 ?
最佳答案
谓词数组和where子句看起来正确定义。在这些行中:
谓词谓词=条件Builder.like(root.get(“ name”),
“%[myValue]%”);
queryConditions.add(predicate);
queryBase.where(queryConditions.toArray(new Predicate[]{}));
TypedQuery<Person> query = em.createQuery(queryBase);
只是提醒。也许您需要
criteriaBuilder.equal
而不是criteriaBuilder.like
。如果您确定自己做了什么,则可以省略此提醒。您需要更改以下几行:
query.setFirstResult(Math.toIntExact(pageRequest.getOffset()));
query.setMaxResults(pageRequest.getPageSize());
return new PageImpl<Person>(query.getResultList(), pageRequest, getTotalCount(criteriaBuilder, queryConditions));
然后为了一致性起见添加
getTotalCount
方法。private Long getTotalCount(CriteriaBuilder criteriaBuilder, Predicate[] predicateArray) {
CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
Root<T> root = criteriaQuery.from(entityType);
criteriaQuery.select(criteriaBuilder.count(root));
criteriaQuery.where(predicateArray);
return entityManager.createQuery(criteriaQuery).getSingleResult();
}