Sitemap
Javarevisited

A humble place to learn Java and Programming better.

Spring Boot | Pagination

Pagination and Sorting in Spring Boot

4 min readJan 25, 2023

--

Why Pagination and Sorting is an efficient approach?

Pagination means dividing a large number of records into multiple parts. It is an important feature to limit the size of your result set to several records that can get efficiently processed by the application and the user.

It is useful when we are presenting data in tabular format on the UI. In case we have fetched 1000 rows as a result, fetching all the data in one shot and showing it to the user at once is not a good idea. In such scenarios, we can use pagination, let’s say 20 rows at a time, and fetch the required data faster.

Given the ability to paginate, one can quickly populate tables and make new REST calls every time the user goes to the next page of the data on the table.

Similarly, sorting data on the backend side is a good approach rather than implementing it on the frontend side. Sorting is done by passing the column name by which we want to sort the query results.

Initial Setup

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "post_blog")
public class Posts {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id" , nullable = false)
private Long id;

@Column(name="title" , nullable = false)
private String title;

@Column(name="content" , nullable = false)
private String content;

@Column(name="description" , nullable = false)
private String description;

@OneToMany(mappedBy = "posts" , cascade = CascadeType.ALL , orphanRemoval = true)
private Set<Comments> comments = new HashSet<>();

Let’s create the Posts entity as our domain class.

Create the PostsRepository and extend it to PagingAndSortingRepository.

@Repository
public interface PostsRepository extends PagingAndSortingRepository<Posts, Long> {
}

PagingAndSortingRepository is the extension of the JpaRepository. So we can extend PostsRepository with JpaRepository too.

Let us create the controller that contains the get-all-posts API.

Generally, paging and sorting parameters are optional and thus part of the request URL as query parameters. If any API supports paging and sorting, ALWAYS provide default values to these parameters — to be used when a user does not specify any paging/sorting preferences.

    @GetMapping({"/get-all-posts"})
public PostResponse getAllPosts(@RequestParam(value = "pageNo", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER, required = false) Integer pageNo,
@RequestParam(value = "pageSize", defaultValue = AppConstants.DEFAULT_PAGE_SIZE, required = false) Integer pageSize,
@RequestParam(value = "sortBy", defaultValue = AppConstants.DEFAULT_SORT_BY, required = false) String sortBy,
@RequestParam(value = "sortDir", defaultValue = AppConstants.DEFAULT_SORT_DIR, required = false) String sortDir) {
return postsService.getAllPosts(pageNo, pageSize);
}
public class AppConstants {
public static final String DEFAULT_PAGE_NUMBER = "0";
public static final String DEFAULT_PAGE_SIZE = "10";
public static final String DEFAULT_SORT_BY = "id";
public static final String DEFAULT_SORT_DIR = "asc";

}

Constant in Java makes the primitive data types immutable. The constants are used in Java to make the program easy to understand and readable.

I have set the parameters pageNo = 0, pageSize = 10, sortBy= “id” and sortDir= “asc” This means, by default, the first page of records will be fetched and each page will be having 10 records. Sorting will be done according to the column id and the sorting direction is ascending.

public interface PostsService {

PostResponse getAllPosts(Integer pageNo , Integer pageSize,String sortBy, String sortDir);

}

Pagination

  1. Create the PageRequest object by passing in the requested page number and the page size.
  2. Create the PageRequest object by passing in the requested page number and the page size.
  3. Pass the PageRequest object as an argument to the repository method we intend to use.
 Pageable pg = PageRequest.of(pageNo , pageSize);
Page<Posts> posts = postsRepository.findAll(pg);

Sorting

  1. Create a Sort object.
  2. Create the Sort object by passing the required column.
  3. Pass the Sort object as an argument to the repository method we intend to use.
Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name())? Sort.by(sortBy).ascending():Sort.by(sortBy).descending();
Page<Posts> posts = postsRepository.findAll(sort);

Pagination and Sorting

We can also implement pagination and sorting together by passing the Sort object into a Pageable object.

@Service
public class PostsServiceImpl implements PostsService {
@Autowired
private PostsRepository postsRepository;

@Override
public PostResponse getAllPosts(Integer pageNo , Integer pageSize, String sortBy , String sortDir){
Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name())? Sort.by(sortBy).ascending():Sort.by(sortBy).descending();
Pageable pg = PageRequest.of(pageNo , pageSize , sort);
Page<Posts> posts = postsRepository.findAll(pg);
List<Posts> postsList = posts.getContent();
List<PostDto> data = postsList.stream().map(this::mapToDTO).collect(Collectors.toList());
PostResponse postResponse = new PostResponse();
postResponse.setData(data);
postResponse.setPageNo(posts.getNumber() + 1);
postResponse.setPageSize(posts.getSize());
postResponse.setTotalElement(posts.getTotalElements());
postResponse.setLast(posts.isLast());
postResponse.setTotalPages(posts.getTotalPages());
return postResponse;

}
}

Let’s try it!

Conclusion

In this blog, we learned how to use pagination and sorting to process a large number of records in Spring JPA using a Spring boot application as an example.

Until next time,

Originally published at on January 25, 2023.

Javarevisited
Javarevisited

Published in Javarevisited

A humble place to learn Java and Programming better.

Prachi Chittora
Prachi Chittora

No responses yet