Pagination and Sorting using Spring Data JPA
This article deeps dive into exposing REST API that supports pagination using Spring DATA JPA.
Introduction
Pagination is a way to get a subset(page) of data on a fixed page and be able to retrieve the pages randomly or sequentially.
Most important parameters are,
Total number of records
Number of records on a page (page size)
Current Page number (page order number) Based on the above informations we can build the algorithm to fetch the respective data. In the SQL world given the current page and page size, we can retrieve the information using limit and offset like follows, Select * from [TABLE NAME] limit pageSize, offset pageNumber*pageSize Spring Data encapsulates all these algorithms/queries and handles all edge cases to return us paginated data.
Total number of records
Number of records on a page (page size)
Current Page number (page order number) Based on the above informations we can build the algorithm to fetch the respective data. In the SQL world given the current page and page size, we can retrieve the information using limit and offset like follows, Select * from [TABLE NAME] limit pageSize, offset pageNumber*pageSize Spring Data encapsulates all these algorithms/queries and handles all edge cases to return us paginated data.
In the next section we will walk through a sample REST API Controller which uses Spring Data JPA to return paginated response.
Implementations
Dish.java
Model class representing Dish object which holds information of about dishes.
@Entity
@Table (name = "dish_table")
public class Dish {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private Long id;
@NotNull
@Size(min=2, message="Name should have atleast 5 characters")
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
@Column(name = "lowprice")
private Double lowPrice;
@Column(name = "highprice")
private Double highPrice;
public Dish () {}
//Getter and Setters
}
DishRepository
Dish Repository extends JpaRepository which extends interface PagingAndSortingRepository that provides methods like
Page findAll(Pageable pageable);. On top of that, we have specified our own method which returns a paginated response and takes a name as the first parameter and Pageable as the second parameter.
@Repository
public interface DishRepository extends JpaRepository {
public Page findByName(String name, Pageable pageable);
}
DishControllerPaginatedV2
Our Rest controller uses repository method findAll(pageRequest). We need to build the pageRequest object and pass it to the repository method. We are getting the pageNo as request parameter.
@RestController
@RequestMapping("api/v2")
public class DishControllerPaginatedV2 {
private static final int pageSize = 2;
@Autowired
DishRepository repo;
@GetMapping(value="/dishes",produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity> getDish3(@RequestParam (defaultValue = "0") int pageNo) throws Exception {
Sort sort = Sort.by("name");
Pageable pageReq = PageRequest.of(pageNo, pageSize, sort);
Page result = repo.findAll(pageReq);
return ResponseEntity.ok(result);
}
}
Invoke REST API
invoking the API with the following curl will provide us paginated response as shown in the next block.
curl --request GET \
--url 'http://localhost:8080/api/v1/dishes3?pageNo=0' \
--header 'cache-control: no-cache'
REST API RESPONSE
{
"content": [
{
"id": 12,
"name": "Anchovies",
"description": "Anchovies",
"lowPrice": 1987,
"highPrice": 0
},
{
"id": 14,
"name": "Celery",
"description": "Celery",
"lowPrice": 2928,
"highPrice": 0
}
],
"pageable": {
"sort": {
"sorted": true,
"unsorted": false,
"empty": false
},
"offset": 0,
"pageNumber": 0,
"pageSize": 2,
"paged": true,
"unpaged": false
},
"last": false,
"totalPages": 7,
"totalElements": 14,
"size": 2,
"number": 0,
"sort": {
"sorted": true,
"unsorted": false,
"empty": false
},
"numberOfElements": 2,
"first": true,
"empty": false
}
Summary
In this article, we saw how to quickly build paginated REST API using Spring Data JPA.
We need to create the PageRequest object and call the repository method findALL(pageRequest).
Spring Data will take care of the offset calculation and will return one page of data along with some important information.
Spring Data also supports filtering and sorting along with pagination.
Bursa
ReplyDeleteMersin
izmir
Rize
Antep
40R851
van
ReplyDeleteerzincan
sivas
ağrı
manisa
EHMHP
uşak evden eve nakliyat
ReplyDeletebalıkesir evden eve nakliyat
tokat evden eve nakliyat
kayseri evden eve nakliyat
denizli evden eve nakliyat
82H
9048D
ReplyDeleteBurdur Evden Eve Nakliyat
Elazığ Evden Eve Nakliyat
Erzurum Evden Eve Nakliyat
Malatya Evden Eve Nakliyat
Bitcoin Nasıl Alınır
85016
ReplyDeleteKastamonu Şehir İçi Nakliyat
Batman Lojistik
Konya Evden Eve Nakliyat
Bingöl Şehirler Arası Nakliyat
Bingöl Lojistik
Aksaray Lojistik
Erzurum Parça Eşya Taşıma
Çerkezköy Sineklik
Adıyaman Parça Eşya Taşıma
908AC
ReplyDeleteTekirdağ Cam Balkon
Pursaklar Parke Ustası
Tekirdağ Çatı Ustası
Kocaeli Parça Eşya Taşıma
Antalya Parça Eşya Taşıma
Bilecik Evden Eve Nakliyat
Trabzon Evden Eve Nakliyat
Şırnak Şehir İçi Nakliyat
Elazığ Şehir İçi Nakliyat
D3F24
ReplyDelete%20 binance komisyon indirimi
6EFDC
ReplyDeleteMazgirt
Üsküdar
Yalıhüyük
İnhisar
Kızılören
Avcılar
Çemişgezek
Yayladere
Ağın
38018
ReplyDeleteBitcoin Nasıl Kazılır
Bitcoin Nasıl Para Kazanılır
Btcst Coin Hangi Borsada
Twitter Retweet Hilesi
Soundcloud Beğeni Satın Al
Coin Nasıl Oynanır
Binance Neden Tercih Edilir
Onlyfans Takipçi Satın Al
Binance Referans Kodu
77FDB
ReplyDeletecanlı sohbet odaları
mexc
kucoin
bybit
mobil 4g proxy
en az komisyon alan kripto borsası
kripto para nasıl alınır
binance referans kod
binance ne demek
3E9CB
ReplyDeletekaldıraç ne demek
https://kapinagelsin.com.tr/
binance referans kimliği nedir
kripto para telegram
sohbet canlı
gate io
binance
kucoin
binance referans kod
C77FE
ReplyDeletegüvenilir ücretli şov
D2D43
ReplyDeletewhatsapp görüntülü show
4B75DAAFF3
ReplyDeleteşov
cam show
görüntülü şov
telegram show
telegram görüntülü şov
ücretli şov
cam şov
whatsapp görüntülü show güvenilir
canli web cam show
AB075DD17E
ReplyDeletevigrande
kaldırıcı
green temptation
kamagra
vega
fx15
lay era
stag
viagra