Sayfalama şu çağrılar ile yapılır
.setFirstResult(offset)
.setMaxResults (pageSize)
.getResultList ()
Örnek
Post nesnelerini çekmek için şöyle yaparız
public List<Post> filterPosts(Integer size, Integer offset) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Post> criteriaQuery = criteriaBuilder.createQuery(Post.class);
Root<Post> root = criteriaQuery.from(Post.class);
// Optional: Add selection criteria/predicates
// List<Predicate> predicates = new ArrayList<>();
// predicates.add(criteriaBuilder.equal(root.get("status"), "published"));
// CriteriaQuery<Post> query = criteriaQuery.where(predicates);
List<Post> postList = entityManager
.createQuery(criteriaQuery)
.setFirstResult(offset)
.setMaxResults(size)
.getResultList();
return postList;
}
Şöyle yaparız
int totalItemsCount(Predicate finalPredicate) {
try {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
Root<Post> root = criteriaQuery.from(Post.class);
// Optional: If joins are involved, you need to specify
// Join<Post, Comments> joinComments = root.join("comments");
return Math.toIntExact(
entityManager.createQuery(
criteriaQuery.select(criteriaBuilder.count(root)).where(finalPredicate))
.getSingleResult());
} catch (Exception e) {
log.error("Error fetching total count: {}", e.getMessage());
}
return 0;
}
Hiç yorum yok:
Yorum Gönder