Create Dynamic Pagination using Java Spring Boot, Hibernate and MySQL


Prerequisite

  • Eclipse IDE or Spring Tool Suite (STS)
  • Mysql installed

We will make a Small application for demonstrating dynamic pagination by dividing large number of data into mutlitple pages with some random data in MySQL using Eclipse IDE with STS plugin installed. Let's Start

  1. Create a Spring Boot project
    1. Click File -> New Project -> Spring Starter Project

    2. Spring Starter Project

    3. After filling the given details click Next


    4. Spring Boot Project

    5. Add JPA, MySQL and Web as dependencies and click Finish

    6. Wait until complete Project is imported successfully


  2. Add Packages, Classes, Jsp pages and xml files in your project as shown in the image below:

      Spring Boot Project hierarchy


  3. HomeController.java
    
    			package com.tutorial.controller;
    
    			import java.util.LinkedHashSet;
    			import java.util.Set;
    
    			import javax.servlet.http.HttpSession;
    
    			import org.springframework.beans.factory.annotation.Autowired;
    			import org.springframework.data.domain.PageRequest;
    			import org.springframework.data.domain.Sort;
    			import org.springframework.stereotype.Controller;
    			import org.springframework.ui.Model;
    			import org.springframework.web.bind.annotation.RequestMapping;
    			import org.springframework.web.bind.annotation.RequestMethod;
    			import org.springframework.web.bind.annotation.RequestParam;
    
    			import com.tutorial.model.User;
    			import com.tutorial.repository.UserRepository;
    
    			@Controller
    			public class HomeController {
    
    			private static final int PAGE_SIZE = 3;			// Number of rows to contain per page
    			private long totalUsersCount;					// total number of rows there in DB
    			@Autowired
    			UserRepository userRepo;
    
    			private PageRequest gotoPage(int page)
    			{
    				PageRequest request = new PageRequest(page,PAGE_SIZE,Sort.Direction.DESC,"id");
    				return request;
    			}
    
    
    			@RequestMapping(value="/", method=RequestMethod.GET)
    			public String index(Model model, HttpSession session, @RequestParam(value="pageNo", required=false, defaultValue = "0") String pageNo) {
    			int lastPageNo;
    			int gotoPageNo=Integer.parseInt(pageNo);
    			Set<User> allUsers=new LinkedHashSet<User>();
    
    				//session.setAttribute("currentPageNo", 0);
    
    				for(User u:userRepo.findAll(gotoPage(gotoPageNo)))			// fetches rows from DB as per Page No
    				{
    					allUsers.add(u);
    				}
    
    
    				totalUsersCount=userRepo.count(); 			//total no of users
    				if(totalUsersCount%PAGE_SIZE!=0)
    				lastPageNo=(int)(totalUsersCount/PAGE_SIZE)+1;					// get last page No (zero based)
    				else
    				lastPageNo=(int)(totalUsersCount/PAGE_SIZE);
    
    
    				model.addAttribute("lastPageNo",lastPageNo);					
    				model.addAttribute("users",allUsers);
    				return "index";
    			}
    
    		}
    
    	


  4. User.java
    
    		package com.tutorial.model;
    
    		import javax.persistence.Column;
    		import javax.persistence.Entity;
    		import javax.persistence.GeneratedValue;
    		import javax.persistence.GenerationType;
    		import javax.persistence.Id;
    		import javax.persistence.Table;
    
    		@Entity
    		public class User {
    
    		@Id
    		@GeneratedValue(strategy=GenerationType.AUTO)
    		@Column(name="id")
    		private Integer id;
    
    		@Column(name = "FirstName")
    		private String firstName;
    
    		@Column(name = "LastName")
    		private String lastName;
    
    		@Column(name = "country")
    		private String country;
    
    		public Integer getId() {
    		return id;
    	}
    
    	public void setId(Integer id) {
    	this.id = id;
    }
    
    
    public String getFirstName() {
    return firstName;
    }
    
    public void setFirstName(String firstName) {
    this.firstName = firstName;
    }
    
    public String getLastName() {
    return lastName;
    }
    
    public void setLastName(String lastName) {
    this.lastName = lastName;
    }
    
    public String getCountry() {
    return country;
    }
    
    public void setCountry(String country) {
    this.country = country;
    }
    
    
    }
    
    


  5. UserRepository.java
    
    		package com.tutorial.repository;
    
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.repository.CrudRepository;
    import org.springframework.stereotype.Repository;
    
    import com.tutorial.model.User;
    
    @Repository
    public interface UserRepository extends CrudRepository<User, Long> {
    
    	public Iterable<User> findAll(Pageable page);
    }
    
    
    	


  6. PaginationTutorialApplication.java
    		package com.tutorial;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.ComponentScan;
    
    @SpringBootApplication
    public class PaginationTutorialApplication {
    
    	public static void main(String[] args) {
    		SpringApplication.run(PaginationTutorialApplication.class, args);
    	}
    }
    
    	


  7. ServletInitializer.java
    
    		package com.tutorial;
    
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
    import org.springframework.context.annotation.Bean;
    import org.springframework.web.servlet.ViewResolver;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    
    public class ServletInitializer extends SpringBootServletInitializer {
    
    	@Override
    	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    		return application.sources(PaginationTutorialApplication.class);
    	}	
    
    }
    
    
    	
  8. application.properties
    		spring.jpa.hibernate.ddl-auto=update
    spring.datasource.url=jdbc:mysql://localhost:3306/tutorial
    spring.datasource.username=root
    spring.datasource.password=
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
    spring.mvc.view.prefix= /WEB-INF/jsp/
    spring.mvc.view.suffix= .jsp
    
    
    spring.jpa.show-sql = true
    
    
    	


  9. index.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Pagination Tutorial</title> </head> <body> <table style="border: 1px solid black;"> <tr style="border: 1px solid black;"> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Country</th> </tr> <c:forEach items="${users}" var="user"> <tr style="border: 1px solid black;"> <td>${user.id }</td> <td>${user.firstName }</td> <td>${user.lastName }</td> <td>${user.country }</td> </tr> </c:forEach> </table> <br> <br> <c:forEach var="i" begin="0" end="${lastPageNo-1 }" > <a href="/?pageNo=${i }">${i+1 }</a>&nbsp;&nbsp;&nbsp;&nbsp; <!-- Displaying Page No --> </c:forEach> </body> </html>


  10. mvc-dispatcher-servlet.xml
    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd" > <context:component-scan base-package="com.tutorial.controller"></context:component-scan> <jpa:repositories base-package="com.tutorial.repository" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <mvc:annotation-driven/> </beans>


  11. web.xml
    <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>Tutorial</display-name> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>


  12. In MySQL DB, Create database named "tutorial" and run the spring application once. After running the spring application, user table would be automatically created in "tutorial" db. Insert this data in "tutorial" Database.
    INSERT INTO `user`(`id`, `first_name`, `last_name`, `country`) VALUES (1,"Virat","Kohli","India"),(2,"MS","Dhoni","India"),(3,"Yuvraj","Singh","India"),(4,"Steve","Smith","Australia"),(5,"Shane","Watson","Australia"),(6,"Rohit","Sharma","India"),(7,"Shikhar","Dhawan","India"),(8,"David","Warner","Australia")
    


  13. pom.xml
    <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorial</groupId> <artifactId>paginationTutorial</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>paginationTutorial</name> <description>App demonstrating simple pagination</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>


Follow these tutorial and you should see a paginated output like this:

Paginated view 1
Fig. Page 1


Note: Data is fetched from the MySQL database in descending order, that's why the ID is in Descending order

Paginated view 2
Fig. Page 2


Paginated view 3
Fig. Page 3
As Database contains 8 rows last page shows remaining 2 rows


If you have any doubt or suggestion, please Comment below.

Solution Worked 7 Upvote
        
Solution Worked 2 Downvote


Comments

1 comment
  • Iqbal

    Very simple post. Thank you




Search
Categories