Create Dynamic Pagination using Java Spring Boot, Hibernate and MySQL
[13872 views]
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
Create a Spring Boot project
Click File -> New Project -> Spring Starter Project
After filling the given details click Next
Add JPA, MySQL and Web as dependencies and click Finish
Wait until complete Project is imported successfully
Add Packages, Classes, Jsp pages and xml files in your project as shown in the image below:
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; // number of rows in Database
@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(HttpSession session, Model model, @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 Database 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";
}
}