I'm fetching the results from DB using criteria and predicates and I got my result list , and I'm trying to apply pagination and sorting but it's not working. Please help me where I'm missing, Here is my code:
private Page<Books> getFiltereBooks(Params params,
PageRequest sortOrder) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Books> criteria = builder.createQuery(Books.class);
Root<Books> booksRoot = criteria.from(Books.class);
List<Predicate> predicates = new ArrayList<Predicate>();
predicates.add(builder.equal(booksRoot.get("id"), params.getRequestId()));
predicates.add(builder.like(builder.lower(booksRoot.get("name")),
"%" + params.getName().toLowerCase() + "%"));
criteria.where(builder.and(predicates.toArray( new Predicate[predicates.size()])));
criteria.orderBy(builder.desc(booksRoot.get("id")));
List<Books> result = em.createQuery(criteria).getResultList();
int total = result.size();
Page<Books> result1 = new PageImpl<>(result, sortOrder, total);
return result1;
}
when I use this code :
Page<Books> result1 = new PageImpl<>(result, sortOrder, total);
it's not working, I want to return a Page Object. any help is appreciated.
You can try this
private Page<Books> getFiltereBooks(Params params,
Pageable pageable) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Books> criteria = builder.createQuery(Books.class);
Root<Books> booksRoot = criteria.from(Books.class);
List<Predicate> predicates = new ArrayList<Predicate>();
predicates.add(builder.equal(booksRoot.get("id"), params.getRequestId()));
predicates.add(builder.like(builder.lower(booksRoot.get("name")),
"%" + params.getName().toLowerCase() + "%"));
criteria.where(builder.and(predicates.toArray( new Predicate[predicates.size()])));
criteria.orderBy(builder.desc(booksRoot.get("id")));
// This query fetches the Books as per the Page Limit
List<Books> result = em.createQuery(criteria).setFirstResult((int) pageable.getOffset()).setMaxResults(pageable.getPageSize()).getResultList();
// Create Count Query
CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
Root<Books> booksRootCount = countQuery.from(Books.class);
countQuery.select(builder.count(booksRootCount)).where(builder.and(predicates.toArray(new Predicate[predicates.size()])));
// Fetches the count of all Books as per given criteria
Long count = em.createQuery(countQuery).getSingleResult();
Page<Books> result1 = new PageImpl<>(result, pageable, count);
return result1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With