Backend programmers know that paging is a common feature in Web systems, and the paging methods I’ve written about are cumbersome and not very portable, which is not encouraging. As a motivated programmer, how can you not know about the PageHelper page plug-in? PageHelper is a very good domestic open source Mybatis paging plug-in, it supports the basic mainstream and common database, consistent support for mysql, Oracle, mariaDB, DB2, SQLite, Hsqldb, etc.. OK, let’s learn about the PageHelper page plugin!

Chinese tutorial

Github project gitosc project

PageHelper use

As for how to use I think the above two projects provided by the absolute force to speak more clearly than I do, the following directly into PageHelper use actual combat

First of all, there are two ways to integrate paging plug-ins. One is to directly download the JAR package and the other is to rely on Mawen. Maven is recommended.

Method 1: Directly download the JAR package

You will need to download jSQLParser.jar because you are using SQL parsing tools

Method 2: Maven adds dependencies

< the dependency > < groupId > com. Making. Pagehelper < / groupId > < artifactId > pagehelper < / artifactId > < version > 5.1.2 < / version > </dependency>Copy the code

1. Import the Maven dependent paging plug-in

I’m using the method two Maven dependency here

2. XML configuration in each case

If myBatis uses PageHelper alone, you need to add the following code to the XML configuration:

<! The plugins must be placed in the correct location in the configuration file, otherwise an error will be reported. , settings? , typeAliases? , typeHandlers? , objectFactory? ,objectWrapperFactory? , plugins? , environments? , databaseIdProvider? , mappers? -- > <! -- com.github. Pagehelper = pageHelper --> <plugins> <! Use the following method to configure the parameters: Recommended by the two projects have all parameters is introduced -- > < plugin interceptor = "com. Making. Pagehelper. PageInterceptor" > < property name = "param1" value="value1"/> </plugin> </plugins>Copy the code

Mybatis is managed by spring’s IOC container, so I need to add the following code to Spring’s XML configuration (added in the creation factory) :

<! - the management to the IOC SqlSessionFactory - > < bean id = "SqlSessionFactory" class = "org. Mybatis. Spring. SqlSessionFactoryBean" > <property name="dataSource" ref="dataSource"/> <! <property name="plugins"> <array> <! Introduced into plug-in - object - > < bean class = "com. Making. Pagehelper. PageInterceptor" > < property name = "properties" > < props > < prop key="helperDialect">oracle</prop> <prop key="reasonable">true</prop> </props> </property> </bean> </array> </property> </bean>Copy the code

Here is a diagram to analyze the two parameters:

3.Controller code writing

The reason why we start with the controller code is because the controller calls the service. It is easier and faster to write the code. To see the difference, the unpaginated Controller code method is as follows:

@Controller
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private IOrdersService ordersService;

// Query all orders without paging
   @RequestMapping("/findAll.do")
    public ModelAndView findAll(a) {
        ModelAndView mv = new ModelAndView();
        List<Orders> ordersList = ordersService.findAll();
        mv.addObject("ordersList", ordersList);
        mv.setViewName("orders-list");
        returnmv; }}Copy the code

With a paging code, it looks like this:

// Take the paging code approach
   @RequestMapping("/findAll.do")
    public ModelAndView findAll(@RequestParam(name="page",required = true,defaultValue = "1")int page,@RequestParam(name="size",required = true,defaultValue = "4")int size ) {
        ModelAndView mv = new ModelAndView();
        List<Orders> ordersList = ordersService.findAll(page,size);

        //PageInfo is a paging Bean
        PageInfo pageInfo =new PageInfo(ordersList);
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("orders-list");
        return mv;

    }
Copy the code

You can see that there are two extra parameters: page and size

4.Service interface code writing

public interface IOrdersService {
    List<Orders> findAll(int page,int size);
}
Copy the code

5.Service implementation class code writing

Before executing SQL (ServiceImpl), PageHelper is used. Parameter pageNum is the page number value. Parameter pageSize represents the number of pages to be displayed per page. In ServiceImpl, the code for paging using PageHelper is as follows:

@Service
public class OrdersServiceImpl implements IOrdersService {
    @Autowired
    private IOrdersDao ordersDao;

    @Override
    public List<Orders> findAll(int page,int size) {
        // Parameter pageNum indicates the page number. Parameter pageSize indicates the number of pages to be displayed on each page
        PageHelper.startPage(page, size);
        returnordersDao.findAll(); }}Copy the code

Pagehelper. startPage(page, size); pageHelper. startPage(page, size); pageHelper. startPage(page, size);

6. JSP page unprocessed code

JSP page code with no changes, general query key change code block, note that the data received here is ordersList

<c:forEach items="${ordersList}" var="orders"> <tr> <td><input name="ids" type="checkbox"></td> ... <td>... </td> </td> </tr> </c:forEach>Copy the code

The code below here is unpaginated logic

<div class="box-tools pull-right"> <ul class="pagination"> <li><a href="#" aria-label="Previous"> home </a> </li> <li><a href="#" aria-label="Previous" Href = "#" > back < / a > < / li > < li > < a href = "#" > 1 < / a > < / li > < li > < a href = "#" > 2 < / a > < / li > < li > < a href = "#" > 3 < / a > < / li > < li > < a Href = "#" > 4 < / a > < / li > < li > < a href = "#" > 5 < / a > < / li > < li > < a href = "#" > page < / a > < / li > < li > < a href = "#" aria - label = "Next" > back < / a > </li> </ul> </div> </div>Copy the code

7. JSP page after processing code

The changed JSP page code, the key change block for the paging query, notice that the data received here is orderslist.list

<c:forEach items="${ordersList.list}" var="orders"> <tr> <td><input name="ids" type="checkbox"></td> ... <td>... </td> </td> </tr> </c:forEach>Copy the code

The code below here is the paging logic

<div class="box-tools pull-right"> <ul class="pagination"> <li> <a href="${pageContext.request.contextPath}/orders/findAll.do? Page =1&size=${pageinfo.pagesize}" aria-label="Previous"> homepage </a> </li> <li><a href="${pageContext.request.contextPath}/orders/findAll.do? Page =${pageinfo.pagene-1}&size=${pageinfo.pagesize}"> </a></li> <c:forEach begin="1" end="${pageinfo.pages}" var="pageNum"> <li><a href="${pageContext.request.contextPath}/orders/findAll.do? page=${pageNum}&size=${pageInfo.pageSize}">${pageNum}</a></li> </c:forEach> <li><a href="${pageContext.request.contextPath}/orders/findAll.do? Page = ${pageInfo. PageNum + 1} & size = ${pageInfo. PageSize} "> page < / a > < / li > < li > < a href="${pageContext.request.contextPath}/orders/findAll.do? Page = ${pageInfo. Pages} & size = ${pageInfo. PageSize} "aria - the label =" Next "> back < / a > < / li > < / ul > < / div > < / div >Copy the code

8. Code analysis before and after JSP page processing

    //PageInfo is a paging Bean
   PageInfo pageInfo =new PageInfo(ordersList);
Copy the code

In order to see the pageInfo source code above, I have posted the code below

package com.github.pagehelper;

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

public class PageInfo<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    private int pageNum;
    private int pageSize;
    private int size;
    private int startRow;
    private int endRow;
    private long total;
    private int pages;
    private List<T> list;
    private int prePage;
    private int nextPage;
    private boolean isFirstPage;
    private boolean isLastPage;
    private boolean hasPreviousPage;
    private boolean hasNextPage;
    private int navigatePages;
    private int[] navigatepageNums;
    private int navigateFirstPage;
    private int navigateLastPage;

    public PageInfo(a) {
        this.isFirstPage = false;
        this.isLastPage = false;
        this.hasPreviousPage = false;
        this.hasNextPage = false;
    }

    public PageInfo(List<T> list) {
        this(list, 8);
    }

    public PageInfo(List<T> list, int navigatePages) {
        this.isFirstPage = false;
        this.isLastPage = false;
        this.hasPreviousPage = false;
        this.hasNextPage = false;
        if (list instanceof Page) {
            Page page = (Page)list;
            this.pageNum = page.getPageNum();
            this.pageSize = page.getPageSize();
            this.pages = page.getPages();
            this.list = page;
            this.size = page.size();
            this.total = page.getTotal();
            if (this.size == 0) {
                this.startRow = 0;
                this.endRow = 0;
            } else {
                this.startRow = page.getStartRow() + 1;
                this.endRow = this.startRow - 1 + this.size; }}else if (list instanceof Collection) {
            this.pageNum = 1;
            this.pageSize = list.size();
            this.pages = this.pageSize > 0 ? 1 : 0;
            this.list = list;
            this.size = list.size();
            this.total = (long)list.size();
            this.startRow = 0;
            this.endRow = list.size() > 0 ? list.size() - 1 : 0;
        }

        if (list instanceof Collection) {
            this.navigatePages = navigatePages;
            this.calcNavigatepageNums();
            this.calcPage();
            this.judgePageBoudary(); }}private void calcNavigatepageNums(a) {
        int i;
        if (this.pages <= this.navigatePages) {
            this.navigatepageNums = new int[this.pages];

            for(i = 0; i < this.pages; ++i) {
                this.navigatepageNums[i] = i + 1; }}else {
            this.navigatepageNums = new int[this.navigatePages];
            i = this.pageNum - this.navigatePages / 2;
            int endNum = this.pageNum + this.navigatePages / 2;
            int i;
            if (i < 1) {
                i = 1;

                for(i = 0; i < this.navigatePages; ++i) {
                    this.navigatepageNums[i] = i++; }}else if (endNum > this.pages) {
                endNum = this.pages;

                for(i = this.navigatePages - 1; i >= 0; --i) {
                    this.navigatepageNums[i] = endNum--; }}else {
                for(i = 0; i < this.navigatePages; ++i) {
                    this.navigatepageNums[i] = i++; }}}}private void calcPage(a) {
        if (this.navigatepageNums ! =null && this.navigatepageNums.length > 0) {
            this.navigateFirstPage = this.navigatepageNums[0];
            this.navigateLastPage = this.navigatepageNums[this.navigatepageNums.length - 1];
            if (this.pageNum > 1) {
                this.prePage = this.pageNum - 1;
            }

            if (this.pageNum < this.pages) {
                this.nextPage = this.pageNum + 1; }}}private void judgePageBoudary(a) {
        this.isFirstPage = this.pageNum == 1;
        this.isLastPage = this.pageNum == this.pages || this.pages == 0;
        this.hasPreviousPage = this.pageNum > 1;
        this.hasNextPage = this.pageNum < this.pages;
    }

    public int getPageNum(a) {
        return this.pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getPageSize(a) {
        return this.pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getSize(a) {
        return this.size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public int getStartRow(a) {
        return this.startRow;
    }

    public void setStartRow(int startRow) {
        this.startRow = startRow;
    }

    public int getEndRow(a) {
        return this.endRow;
    }

    public void setEndRow(int endRow) {
        this.endRow = endRow;
    }

    public long getTotal(a) {
        return this.total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public int getPages(a) {
        return this.pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public List<T> getList(a) {
        return this.list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    / * *@deprecated* /
    @Deprecated
    public int getFirstPage(a) {
        return this.navigateFirstPage;
    }

    / * *@deprecated* /
    @Deprecated
    public void setFirstPage(int firstPage) {
        this.navigateFirstPage = firstPage;
    }

    public int getPrePage(a) {
        return this.prePage;
    }

    public void setPrePage(int prePage) {
        this.prePage = prePage;
    }

    public int getNextPage(a) {
        return this.nextPage;
    }

    public void setNextPage(int nextPage) {
        this.nextPage = nextPage;
    }

    / * *@deprecated* /
    @Deprecated
    public int getLastPage(a) {
        return this.navigateLastPage;
    }

    / * *@deprecated* /
    @Deprecated
    public void setLastPage(int lastPage) {
        this.navigateLastPage = lastPage;
    }

    public boolean isIsFirstPage(a) {
        return this.isFirstPage;
    }

    public void setIsFirstPage(boolean isFirstPage) {
        this.isFirstPage = isFirstPage;
    }

    public boolean isIsLastPage(a) {
        return this.isLastPage;
    }

    public void setIsLastPage(boolean isLastPage) {
        this.isLastPage = isLastPage;
    }

    public boolean isHasPreviousPage(a) {
        return this.hasPreviousPage;
    }

    public void setHasPreviousPage(boolean hasPreviousPage) {
        this.hasPreviousPage = hasPreviousPage;
    }

    public boolean isHasNextPage(a) {
        return this.hasNextPage;
    }

    public void setHasNextPage(boolean hasNextPage) {
        this.hasNextPage = hasNextPage;
    }

    public int getNavigatePages(a) {
        return this.navigatePages;
    }

    public void setNavigatePages(int navigatePages) {
        this.navigatePages = navigatePages;
    }

    public int[] getNavigatepageNums() {
        return this.navigatepageNums;
    }

    public void setNavigatepageNums(int[] navigatepageNums) {
        this.navigatepageNums = navigatepageNums;
    }

    public int getNavigateFirstPage(a) {
        return this.navigateFirstPage;
    }

    public int getNavigateLastPage(a) {
        return this.navigateLastPage;
    }

    public void setNavigateFirstPage(int navigateFirstPage) {
        this.navigateFirstPage = navigateFirstPage;
    }

    public void setNavigateLastPage(int navigateLastPage) {
        this.navigateLastPage = navigateLastPage;
    }

    public String toString(a) {
        StringBuffer sb = new StringBuffer("PageInfo{");
        sb.append("pageNum=").append(this.pageNum);
        sb.append(", pageSize=").append(this.pageSize);
        sb.append(", size=").append(this.size);
        sb.append(", startRow=").append(this.startRow);
        sb.append(", endRow=").append(this.endRow);
        sb.append(", total=").append(this.total);
        sb.append(", pages=").append(this.pages);
        sb.append(", list=").append(this.list);
        sb.append(", prePage=").append(this.prePage);
        sb.append(", nextPage=").append(this.nextPage);
        sb.append(", isFirstPage=").append(this.isFirstPage);
        sb.append(", isLastPage=").append(this.isLastPage);
        sb.append(", hasPreviousPage=").append(this.hasPreviousPage);
        sb.append(", hasNextPage=").append(this.hasNextPage);
        sb.append(", navigatePages=").append(this.navigatePages);
        sb.append(", navigateFirstPage=").append(this.navigateFirstPage);
        sb.append(", navigateLastPage=").append(this.navigateLastPage);
        sb.append(", navigatepageNums=");
        if (this.navigatepageNums == null) {
            sb.append("null");
        } else {
            sb.append('[');

            for(int i = 0; i < this.navigatepageNums.length; ++i) {
                sb.append(i == 0 ? "" : ",").append(this.navigatepageNums[i]);
            }

            sb.append('] ');
        }

        sb.append('} ');
        returnsb.toString(); }}Copy the code

Here, basic OK, I once again emphasize the two projects I recommend, which is very detailed big guy wrote, emphasize finished, wave paw ~