springhibernatejpaspring-data-jpa

Implementing Pagination using entity manager in spring


How can I implement pagination in Spring + hibernate project ? Following is the code. I will get PageRequest object and I want to return Page of item

 @Repository
    public class ItemRepository {

      @PersistenceContext
      EntityManager entityManager;

      public Page<Item> findItems(PageRequest pageRequest) {
        // TODO: Implement me
        return new Page<>(new ArrayList<>(), 0, 0);
      }
    }


    public class PageRequest {

      private final int count;
      private final int pageNumber;

      public PageRequest(int pageNumber, int count) {
        assert pageNumber >= 0;
        assert count > 0;

        this.pageNumber = pageNumber;
        this.count = count;
      }

      public int getCount() {
        return count;
      }

      public int getPageNumber() {
        return pageNumber;
      }
    }

Solution

  • I found the solution

    public Page<Item> findItems(PageRequest pageRequest) {
    
        Query query = entityManager.createQuery("From Item");
        int pageNumber =pageRequest.getPageNumber();
        int pageSize = pageRequest.getCount();
        query.setFirstResult((pageNumber) * pageSize);
        query.setMaxResults(pageSize);
        List <Item> fooList = query.getResultList();
    
        Query queryTotal = entityManager.createQuery
                ("Select count(f.id) From Item f");
        long countResult = (long)queryTotal.getSingleResult();
        int i=(int)countResult;
       return new PageImpl<>(fooList, pageRequest.getPageNumber(), i);
      }
    

    I had to query two times to DB once to get records and then to get all the count.