Java Paging Principle

Posted by moonoo1974 on Sat, 11 May 2019 17:12:42 +0200

Links to the original text: https://blog.csdn.net/winfredzen/article/details/52104251
Java paging
Common paging types:

Traditionally, using the traditional paging method, data information can be clearly obtained, such as how many pieces of data, how many pages to display and so on.
Drop-down pagination: Pull-down pagination is generally not able to obtain a clear amount of data related information, but after the pagination operation, you can still see the data queried before.
Common paging implementations:

Paging is implemented using subList (int start index, int end index) method in List interface
Paging directly using database SQL statements
Paging across databases using frameworks such as hibernate
Paging with subList()

The subList (int start index, int end index) method in the List interface is used to return a partial view between the fromIndex (including) and endIndex (excluding) specified in the list.


Paging Using Database SQL Statement
mysql database uses limit keyword, oracle uses rownum keyword.
For example, the top ten data are queried from the student table (t_student).
MySql Query Statement

select * from t_student limit 0, 10

Represents taking 10 records from Article 0.

PostgreSQL Query Statement

select * from t_student limit 10 offset 0

Oracle Query Statement

Paging across databases using hibernate Framework

Comparisons of Paging Implementation

Realization way
Model object
In addition to dealing with the objects of the mapped data table, a Pager paging object is created, which roughly reads as follows:

package com.imooc.page.model;

import java.io.Serializable;
import java.util.List;

public class Pager<T> implements Serializable {

    private static final long serialVersionUID = -8741766802354222579L;

    //How many records are displayed per page
    private int pageSize;
    //Current Page Data
    private int currentPage;
    //How many records are there altogether?
    private int totalRecord;
    //How many pages of records are there?
    private int totalPage;
    //To display data, use generics
    private List<T> dataList;

    public Pager() {
        super();
    }

    public Pager(int pageSize, int currentPage, int totalRecord, int totalPage, List<T> dataList) {
        super();
        this.pageSize = pageSize;
        this.currentPage = currentPage;
        this.totalRecord = totalRecord;
        this.totalPage = totalPage;
        this.dataList = dataList;
    }

    public Pager(int pageNum, int pageSize, List<T> sourceList){
        if (sourceList == null){
            return;
        }

        //Total number of records
        this.totalRecord = sourceList.size();
        //How many records are displayed per page
        this.pageSize = pageSize;
        //Get the total number of pages
        this.totalPage = this.totalRecord / this.pageSize;
        if (this.totalRecord % this.pageSize != 0) {
            this.totalPage += 1;
        }

        //Current Page Data
        this.currentPage = this.totalPage < pageNum ? this.totalPage : pageNum;

        //Initial index
        int fromIndex = this.pageSize * (this.currentPage - 1);
        //End index
        int toIndex =this.pageSize * this.currentPage > this.totalRecord ?  this.totalRecord :  this.pageSize * this.currentPage;

        this.dataList = sourceList.subList(fromIndex, toIndex);
    }

    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public int getCurrentPage() {
        return currentPage;
    }
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }
    public int getTotalRecord() {
        return totalRecord;
    }
    public void setTotalRecord(int totalRecord) {
        this.totalRecord = totalRecord;
    }
    public int getTotalPage() {
        return totalPage;
    }
    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }
    public List<T> getDataList() {
        return dataList;
    }
    public void setDataList(List<T> dataList) {
        this.dataList = dataList;
    }
    public static long getSerialversionuid() {
        return serialVersionUID;
    }



}

hibernate paging
The implementation of Dao is as follows:

package com.imooc.page.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;

import com.imooc.page.Constant;
import com.imooc.page.HibernateSessionFactory;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;

public class HibernateStudentDaoImpl implements StudentDao{

    @SuppressWarnings("unchecked")
    @Override
    public Pager<Student> findStudent(Student searchModel, int pageNum, int pageSize) {
        Pager<Student> result = null;

        //Store query parameters
        Map<String, Object> paramMap = new HashMap<String, Object>();

        String stuName = searchModel.getStuName();
        int gender = searchModel.getGender();

        StringBuilder hql = new StringBuilder(" from Student where 1=1");
        StringBuilder countHql = new StringBuilder("select count(id) from Student where 1=1");

        if(stuName != null && !stuName.equals("")){
            hql.append(" and stuName like :stuName");
            countHql.append(" and stuName like :stuName");
            paramMap.put("stuName","%" + stuName + "%");
        }

        if(gender == Constant.GENDER_MALE  || gender == Constant.GENDER_FEMALE){
            hql.append(" and gender = :gender");
            countHql.append(" and gender = :gender");
            paramMap.put("gender",gender);
        }

        //Initial index
        int fromIndex = pageSize * (pageNum - 1);

        List<Student> studentList = new ArrayList<Student>();

        Session session = null;

        try {

            session = HibernateSessionFactory.getSession();
            //Get the query object
            Query hqlQuery = session.createQuery(hql.toString());
            Query countHqlQuery = session.createQuery(countHql.toString());
            //Setting Query Parameters
            setQueryParams(hqlQuery, paramMap);
            setQueryParams(countHqlQuery, paramMap);

            //Query from which record
            hqlQuery.setFirstResult(fromIndex);
            //How many records are queried in total?
            hqlQuery.setMaxResults(pageSize);

            //Get the results of the query
            studentList = hqlQuery.list();
            //Get the total number of entries
            List<?> countResult = countHqlQuery.list();

            int totalRecord = ((Number)countResult.get(0)).intValue();
            //Get the total number of pages
            int totalPage = totalRecord / pageSize;
            if (totalRecord % pageSize != 0) {
                totalPage += 1;
            }

            //Assemble pager
            result  = new Pager<>(pageSize, pageNum, totalRecord, totalPage, studentList);


        } catch (Exception e) {
            throw new RuntimeException("Query all data exceptions!", e);
        }finally {
            if (session != null) {
                HibernateSessionFactory.closeSession();
            }
        }

        return result;  
    }

    /**
     * Setting Query Parameters
     * @param query
     * @param paramMap
     * @return
     */
    private Query setQueryParams(Query query, Map<String, Object> paramMap){
        if(paramMap != null && !paramMap.isEmpty()){
            for(Map.Entry<String, Object> param : paramMap.entrySet()){
                query.setParameter(param.getKey(), param.getValue());
            }
        }
        return query;
    }

}

The corresponding Servlet is as follows, where fastjson is used to return json data:

package com.imooc.page.servlet;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.imooc.page.Constant;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
import com.imooc.page.service.HibernateStudentServiceImpl;
import com.imooc.page.service.StudentService;
import com.imooc.page.util.StringUtil;

public class HibernateDataServlet extends HttpServlet {

    private StudentService studentService = new HibernateStudentServiceImpl();

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Receive the parameters in the request
        String stuName = request.getParameter("stuName"); //Student name

        // Obtaining Students'Gender
        int gender = Constant.DEFAULT_GENDER;
        String genderStr = request.getParameter("gender");
        if(genderStr!=null && !"".equals(genderStr.trim())){
            gender = Integer.parseInt(genderStr);
        }

        // Check the validity of pageNum parameter input
        String pageNumStr = request.getParameter("pageNum"); 
        if(pageNumStr !=null && !StringUtil.isNum(pageNumStr)){
            request.setAttribute("errorMsg", "Parameter transfer error");
            request.getRequestDispatcher("jdbcSqlStudent.jsp").forward(request, response);
            return;
        }

        int pageNum = Constant.DEFAULT_PAGE_NUM; //Display page number of data
        if(pageNumStr!=null && !"".equals(pageNumStr.trim())){
            pageNum = Integer.parseInt(pageNumStr);
        }

        int pageSize = Constant.DEFAULT_PAGE_SIZE;  // How many records are displayed per page
        String pageSizeStr = request.getParameter("pageSize");
        if(pageSizeStr!=null && !"".equals(pageSizeStr.trim())){
            pageSize = Integer.parseInt(pageSizeStr);
        }

        // Assembly query conditions
        Student searchModel = new Student(); 
        searchModel.setStuName(stuName);
        searchModel.setGender(gender);

        //Call service to get query results
        Pager<Student> result = studentService.findStudent(searchModel, 
                                                                pageNum, pageSize);
        //No caching
        response.setHeader("Cache-Control", "no-cache");  
        response.setHeader("Pragma", "no-cache");  
        //Set timeout to0
        response.setDateHeader("Expires", 0);  
        //Set the encoding format to utf-8
        response.setContentType("text/html;charset=utf-8");

        //json format for retrieving query data
        String responseStr = JSON.toJSONString(result);
        //Write data to response
        Writer writer = response.getWriter();
        writer.write(responseStr);
        writer.flush();
    }

    public static void main(String[] args) {
        String s = String.format("%05d", 123);
        System.out.println(s);
    }

}

jPaginate
gbirke/jquery_pagination
jQuery Pagination plugin Optimized for bootstra

Reference resources
The Principle and Practice of Java Paging (Part I)
The Principle and Practice of Java Paging (Part 2)

Topics: Java Session Hibernate JSON