Paging with Spring Data

This blog shows by an example on how to use paging support in Spring Data. Let start with following repository without paging

 

public interface ProductRepository extends JpaRepository<Product, Long> {

 @Query("SELECT p FROM product p WHERE p.category= :category")
 List<Product> findByCategory(@Param("category") String category);

}

 

The above query will return all products with matching category. To change it to only return products required to fill in a single page,  the method is updated to:

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
...
public interface ProductRepository extends JpaRepository<Product, Long> {

 @Query("SELECT p FROM product p WHERE p.category= :category")
 Page<Product> findByCategory(@Param("category") String category, 
     Pageable pageable);

}

Note:

  1. The method now returns an object with class Page instead of List
  2. A new argument with type Pageable is added

The Pageable argument allows you to specify a few things including which page to return, the number of items in each page and properties used to sort the results. For example, to return the 2nd page where size of each page is 10, the method can be called with Pageable below

Pageable pageable = new PageRequest(1, 10);

Class PageRequest is a concrete implementation of Pageable provided by Spring Data. Note page number is 0-indexed.

To define how the results should be ordered, a Sort object can be supplied as the 3rd argument of the PageRequest constructor. For example, to return list of products sorted from highest price and then by name in alphabetical order:

Sort sort = new Sort(new Order(Direction.DESC, "price"), 
                     new Order(Direction.ASC, "name"));

Pageable pageable = new PageRequest(1, 10, sort);

Finally, note that the Page object returned from the method contains not just the list of products but also other values useful for implementing pagination, e.g. total number of results, number of pages. See the javadoc here for more detail.

 

 

Advertisements

About Raymond Lee
Professional Java/EE Developer, software development technology enthusiast.

Comments are closed.