Pagination With JPA Introduction#
Dependencies#
- First, you need to add some dependencies below into your
pom.xml. In this example I will usemysql database. You can choose other databases if you like, Database Configuration In SpringBoot maybe is helpful for you.
| pom.xml | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
Implementation#
Entity And Models#
- First, you need to create an
Entitywhich will reflect with the table in your database and It will be the object for manipulation information between JPA and Database. Below is my exampleEntity
| PostEntity.java | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
- Next, We will create a model for filter request which contains some information like
current page,number of item in page,sort fieldandsort order.
| Filter.java | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | |
- Then create a model for response result.
| PostResponse.java | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | |
RESPOSITORY#
- Now, you need to create a
Respositorywhich will be the layer to help you do queries and get results from your database, because we are using JPA for paging and sorting so we will extend our repository fromPagingAndSortingRepositorythat JPA provided.
| PostPagingRepository.java | |
|---|---|
1 2 3 4 5 6 7 8 9 | |
Service#
- So now, you can create a
Serviceand put some implementation code as below. Note that because we are extending our repository fromPagingAndSortingRepositoryso we have to usePageableandPageof JPA as the object for queries and response results from database, respectively.
| TodoServiceImpl.java | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
Controller#
- Finally, let's create a simple controller with an filter api and inject your service for using.
| ApiController.java | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
Testing#
- Using postman and call to your api with filter body as below
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | |