Mybatis pagination plug PageHelper learning and use

table of Contents

Back-end programmers know, in Web systems, paging is a common feature that I wrote before paging methods are more trouble, portability is not high, which is very optimistic. As a positive and cheerful programmer, how you can not understand PageHelper pagination plug it? PageHelper is mybatis pagination plug-domestic excellent open-source, which supports basic mainstream and common database, unanimous support mysql, oracle, mariaDB, DB2, SQLite, Hsqldb and so on. OK Then take a learn to understand PageHelper pagination plug!
@

Chinese Course

First, the recommended two PageHelper pagination plug-in project address, and there are Chinese Tutorial:
GitHub project
gitosc project

PageHelper use

As for how I want to use the above two projects speak absolutely forced to speak better than I do, use the following directly into combat PageHelper

First, the introduction of an integrated plug tab by the following two ways, one is directly under one is mawen dependent jar package, recommended Maven manner .

Method One: Direct download jar package

Download jar package , due to the use of the sql analytical tool, you also need to download jsqlparser.jar

Method two: Maven add dependencies

  <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.2</version>
  </dependency>

1. Import maven dependent tab widget

I'm here on the use of two methods rely maven
Here Insert Picture Description

2. xml in each case of the configuration

情况一: If mybatis separate plug tab PageHelper time, you need to add the following code in the xml configuration:

  <!--
plugins在配置文件中的位置必须符合要求,否则会报错,顺序如下properties?, settings?,
 typeAliases?, typeHandlers?, objectFactory?,objectWrapperFactory?, plugins?, 
 environments?, databaseIdProvider?, mappers?
  -->
  <!-- com.github.pagehelper为PageHelper类所在包名 -->
    <plugins> 
    <!-- 使用下面的方式配置参数,推荐的两个项目中有所有的参数介绍 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor"> 
            <property name="param1" value="value1"/>
        </plugin>
    </plugins>

情况二: Obviously, I was ssm this project, the mybatis spring is handed over to the IOC container management , you need to add the following code in the xml configuration spring (Add to create the factory):

  <!-- 把交给IOC管理 SqlSessionFactory -->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
     <property name="dataSource" ref="dataSource"/>
     <!-- 传入PageHelper的插件 -->
     <property name="plugins">
         <array>
             <!-- 传入插件的对象 -->
             <bean class="com.github.pagehelper.PageInterceptor">
                 <property name="properties">
                     <props>
                         <prop key="helperDialect">oracle</prop>
                         <prop key="reasonable">true</prop>
                     </props>
                 </property>
             </bean>
         </array>
     </property>
 </bean>

Here with a map to analyze the effect of two parameters:
Here Insert Picture Description
For more information, please refer to the above recommended project ~

3.Controller coding

We finished the configuration above, as to why the start of the code from the controller because the controller is calling service Well, write something more convenient! In order to see the difference, controller nonpaged code means as follows:

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

    @Autowired
    private IOrdersService ordersService;

//查询所有orders未分页
   @RequestMapping("/findAll.do")
    public ModelAndView findAll() {
        ModelAndView mv = new ModelAndView();
        List<Orders> ordersList = ordersService.findAll();
        mv.addObject("ordersList", ordersList);
        mv.setViewName("orders-list");
        return mv;
    }
}

The use of paging codes is as follows:

//采用分页代码方法
   @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就是一个分页Bean
        PageInfo pageInfo =new PageInfo(ordersList);
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("orders-list");
        return mv;

    }

You can find more than two parameters are pageandsize

4.Service write interface code

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

5.Service implementation class coding

Before (the ServiceImpl) performed sql, PageHelper using paging, the parameter pageNumis a parameter page number pageSizerepresentative of the number of a page display. In ServiceImpl using PageHelper paging operation code is as follows:

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

    @Override
    public List<Orders> findAll(int page,int size) {
        //参数pageNum 是页码值   参数pageSize 代表是每页显示条数
        PageHelper.startPage(page, size);
        return ordersDao.findAll();
    }
}

Special Note: When writing PageHelper paged code of PageHelper.startPage(page, size)the sentence must be written on a query method, the middle can not add any code, or failure!
Here Insert Picture Description

6.jsp page untreated Code

jsp page code is not changed, the general poll key to change the code block, note data received here ordersList

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

This code is the following logic code nonpaged

 <div class="box-tools pull-right">
                        <ul class="pagination">
                            <li>
                                <a href="#" aria-label="Previous">首页</a>
                            </li>
                            <li><a href="#">上一页</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="#">下一页</a></li>
                            <li>
                                <a href="#" aria-label="Next">尾页</a>
                            </li>
                        </ul>
                    </div>

                </div>

7.jsp page treatment codes

jsp page code changes, key changes paging query code block, note data received here ordersList.list

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

This code is paged following logic code

<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">首页</a>
        </li>
        <li><a href="${pageContext.request.contextPath}/orders/findAll.do?page=${pageInfo.pageNum-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}">下一页</a></li>
        <li>
            <a href="${pageContext.request.contextPath}/orders/findAll.do?page=${pageInfo.pages}&size=${pageInfo.pageSize}" aria-label="Next">尾页</a>
        </li>
    </ul>
</div>
</div>

8.jsp page before and after handling code analysis

Here Insert Picture Description
Here Insert Picture Description

    //PageInfo就是一个分页Bean
   PageInfo pageInfo =new PageInfo(ordersList);

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

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() {
        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() {
        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() {
        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() {
        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() {
        return this.pageNum;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    public int getNavigatePages() {
        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() {
        return this.navigateFirstPage;
    }

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

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

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

    public String toString() {
        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('}');
        return sb.toString();
    }
}

Here, basically OK, I stress again that I recommend two projects, that there is more telling big brother wrote, emphasizing completed, waving claws ~

Guess you like

Origin www.cnblogs.com/yichunguo/p/11974596.html