AI Hints
Home›Spring Boot Tutorial›Paging, @Query with JPQL and Native Queries
Spring Boot · Lesson 58 of 120

Paging

One page at a time.

⏱ 2 min read▶ Video at 1:18:18🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

A shop might have a million books. Sending them all at once would be slow, and nobody can read them anyway. So we send one page at a time.

  • A million books
  • Too slow to send
  • One page at a time

Pageable and Page

Page Request dot of makes a Pageable, a page number, and a page size. Page numbers start at zero. It can include a Sort too. The result is a Page. It holds this page's books, plus the total count, and the number of pages.

keyvalue
PageRequest.of(0, 3)page 0, size 3
Numbersstart at 0
Page<Book>content + totals
Alsosorting inside

A paged query

Any query method can take a Pageable as its last parameter. Then it returns a Page, instead of a list.

BookRepository.javajava
public interface BookRepository extends JpaRepository<Book, Long> {

    Page<Book> findByPriceLessThan(double max, Pageable pageable);
}

Reading pages

Find all takes a page request, for page zero, with three books, sorted by title. Get content gives the books on that page. Get total elements, and get total pages, give the totals. Page two, the third page, is the last one. And our own query is paged too. Run it. The first page has three books. There are eight books, in three pages. The last page has only two books. And the cheap books fill two pages.

QueryDemo.javajava
@Component
public class QueryDemo implements CommandLineRunner {

    private final BookRepository books;

    public QueryDemo(BookRepository books) { this.books = books; }

    @Override
    public void run(String... args) {
        Page<Book> page = books.findAll(PageRequest.of(0, 3, Sort.by("title")));
        System.out.println("Page 1: " + page.getContent());
        System.out.println("Total books: " + page.getTotalElements());
        System.out.println("Total pages: " + page.getTotalPages());
        Page<Book> last = books.findAll(PageRequest.of(2, 3, Sort.by("title")));
        System.out.println("Page 3: " + last.getContent() + ", last? " + last.isLast());
        var cheap = books.findByPriceLessThan(9, PageRequest.of(0, 2));
        System.out.println(cheap.getTotalPages() + " cheap pages: " + cheap.getContent());
    }
}
Output
Page 1: [Book 4: Children of Dune (8.49), Book 3: Circe (10.99), Book 1: Dune (9.99)]
Total books: 8
Total pages: 3
Page 3: [Book 6: The Fellowship of the Ring (11.99), Book 2: The Hobbit (8.99)], last?
true
2 cheap pages: [Book 2: The Hobbit (8.99), Book 4: Children of Dune (8.49)]
Also uses Book.java
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    private double price;

    protected Book() {}

    public Book(String title, String author, double price) {
        this.title = title; this.author = author; this.price = price;
    }

    public Long getId() { return id; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }

    @Override
    public String toString() { return "Book " + id + ": " + title + " (" + price + ")"; }
}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {

    Page<Book> findByPriceLessThan(double max, Pageable pageable);
}
Also uses data.sql
INSERT INTO book (title, author, price) VALUES
  ('Dune', 'Frank Herbert', 9.99),
  ('The Hobbit', 'J.R.R. Tolkien', 8.99),
  ('Circe', 'Madeline Miller', 10.99),
  ('Children of Dune', 'Frank Herbert', 8.49),
  ('Song of Achilles', 'Madeline Miller', 9.49),
  ('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
  ('Emma', 'Jane Austen', 6.99),
  ('Persuasion', 'Jane Austen', 7.49);
Also uses application.properties
spring.jpa.defer-datasource-initialization=true

Summary

Pass a Page Request, and get back a Page, with the content and the totals. Page numbers start at zero. Next, writing our own queries, with at Query.

Key takeaways
  • PageRequest.of(page, size)
  • Page<Book>
  • getTotalPages()
Next up: @Query with JPQL — write your own query