Creating Pagination in Spring Data JPA

28,384

Solution 1

I've seen similar problem last week, but can't find it so I'll answer directly.

Your problem is that you specify the parameters too late. Pageable works the following way: you create Pageable object with certain properties. You can at least specify:

  1. Page size,
  2. Page number,
  3. Sorting.

So let's assume that we have:

PageRequest p = new PageRequest(2, 20);

the above passed to the query will filter the results so only results from 21th to 40th will be returned.

You don't apply Pageable on result. You pass it with the query.

Edit:

Constructors of PageRequest are deprecated. Use Pageable pageable = PageRequest.of(2, 20);

Solution 2

The constructors of Pageable are deprecated, use of() instead:

Pageable pageable = PageRequest.of(0, 20);
Share:
28,384
Tejas
Author by

Tejas

Updated on October 18, 2020

Comments

  • Tejas
    Tejas over 3 years

    I am trying to implement pagination feature in Spring Data JPA. I am referring this Blog My Controller contains following code :

     @RequestMapping(value="/organizationData", method = RequestMethod.GET)
      public String list(Pageable pageable, Model model){
        Page<Organization> members = this.OrganizationRepository.findAll(pageable);
        model.addAttribute("members", members.getContent());
        float nrOfPages = members.getTotalPages();
        model.addAttribute("maxPages", nrOfPages);
        return "members/list"; 
      }
    

    My DAO is following :

    @Query(value="select m from Member m", countQuery="select count(m) from Member m")
      Page<Organization> findMembers(Pageable pageable);
    

    I am able to show first 20 records, how do I show next 20??? Is there any other pagination example that I can refer??

  • rbawaskar
    rbawaskar about 5 years
    Note: Index is zero-based page index.
  • J3ernhard
    J3ernhard over 4 years
    new PageRequest() constructor is deprecated
  • xenteros
    xenteros over 4 years
    @J3ernhard it wasn't when this answer was prepared.
  • J3ernhard
    J3ernhard over 4 years
    @xenteros that's right, further information about PageRequest: stackoverflow.com/q/44848653/4121281
  • Sandeep Kumar
    Sandeep Kumar over 4 years
    how to set page size unlimited?
  • xenteros
    xenteros over 4 years
    @SandeepKumar what do you mean, by setting the unlimited page size?
  • Sandeep Kumar
    Sandeep Kumar over 4 years
    I was writing a wrapper on top of an existing paginated API to fetch all record, I did it by passing Integer.Max_Value.
  • Dimitri Kopriwa
    Dimitri Kopriwa almost 4 years
    PageRequest p = new PageRequest(2, 20); can't be passed to spring data
  • Dimitri Kopriwa
    Dimitri Kopriwa almost 4 years
    This doesn't exist in my version of spring, how can I create a peageable object to limit the query to 1?
  • masterxilo
    masterxilo almost 3 years
    Use PageRequest.of instead of constructor