This post would demo how to do pagination operations by using springboot 2 and JPA.
2. Environments
SpringBoot 2.0.2+
spring-boot-starter-jpa
spring-boot-starter-web
MySQL connector java
Lombok
Java 1.8+
3. The Pom.xml
spring boot version:
all dependencies:
4. The dependencies explanation
4.1 The lombok
The lombok is an IDE plugin to help you do some boliertemplate jobs. In this post we use the lombok to generate the getter/setter of the domain object.
You can refer to this post to learn how to use lombok.
5. The project layout
6. The database , table and initial data
For demo purpose, I setup one database in localhost as follows:
There is a table ‘tbl_student’ in both of the databases:
And insert five records into that table:
Here we insert 11 records to test the pagination, we need two pages, each page with 10 records.
7. The domain class Student
Here we use the lombok @Data annotation to generate getter/setter and constructors for the Student class.
We define the id property as the @Id of the table ,and specify the GenerationType.IDENTITY to it, which means the id is auto-increment.
We define the table name by @Table annotation
7. The app codes
7.1 the application.properties
Supply these properties in your application.properties:
7.2 The StudentPageRepository interface
The dao.StudentPageRepository is as follows:
The class StudentPageRepository only extends from the PagingAndSortingRepository ,there is no need to define any other methods to implement the pagination operations.
There are two methods in the PagingAndSortingRepository:
Iterable findAll(Sort var1);
sort by the var1 rule and return an Iterable
Page findAll(Pageable var1);
do pagination and sorting by the var1 rule and return Page
Notice that there are sort criteria in the Pageable object.
7.3 The Testcase
The StudentPageTest class would test the pagination operations:
Run the testcase, we got a green bar.
7.4 The RestController and the Service layer
We want to test the pagination with the spring mvc RestController
We create a service to interact with the RestController
Then we create a RestController:
Run the app:
Test with the postman like this:
It’s so easy, do you think so?
The example source code has been uploaded to github, you can visit here to view the example source codes.