The realization of paging and the use of Mybatis's paging plug-in PageHelper

The realization of paging and the use of PageHelper

When working on a project, paging is a very common small function, but it usually has a very cumbersome package. Here is a very useful plug-in — — — — paging plug-in pageHelper, which can meet the basic needs of our work.

Introduction to PageHelper

PageHelper is a very good open source mybatis plugin in China. It supports basic mainstream and commonly used databases, such as mysql, oracle, DB2, SQLite, Hsqldb, etc.
The project address of this project on github: https://github. com/pagehelper/Mybatis-PageHelper

The use of PageHelper
configuration introduction

Use Maven to add the following dependencies in pom.xml.
First, you need to introduce the corresponding dependencies

<!--分页工具包-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
</dependency>

The relevant configuration is as follows.
Pay special attention that the new version of the interceptor is com.github.pagehelper.PageInterceptor. com.github.pagehelper.PageHelper is now a special dialect implementation class, which is the default implementation class of the paging plug-in, providing the same usage as before.

1. Configure the interceptor plug-in in the MyBatis configuration xml

<plugins>
    <!-- com.github.pagehelper为PageInterceptor类所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <property name="reasonable" value="true"/>
    </plugin>
</plugins>`

2. Configure the interceptor in the Spring configuration file. The
above configuration can also not be configured in mybatis.xml, or it can be configured in SqlSessionFactoryBean in spring-mybatis.xml. The code is as follows:

<!-- SqlSessionFactoryBean -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
 <!--分页插件配置-->
    <property name="plugins">
        <array>
            <bean class="com.github.pagehelper.PageInterceptor">
                <!--配置分页属性-->
                <property name="properties">
                    <props>
                        <!--指定数据库方言-->
                        <prop key="helperDialect">mysql</prop>
                        <!--合理化分页操作-->
                        <prop key="reasonable">true</prop>
                    </props>
                </property>
            </bean>
        </array>
    </property>
</bean>

Related parameter introduction

The helperDialect
paging plugin will automatically detect the current database link and automatically select the appropriate paging method. You can configure the helperDialect property to specify which dialect the paging plugin uses. When configuring, you can use the following abbreviated values:
oracle, mysql, mariadb, sqlite, hsqldb, postgresql, db2, sqlserver, informix, h2, sqlserver201

The
default value of rowBoundsWithCount is false. This parameter is valid when RowBounds is used as a paging parameter. When this parameter is set
to true, use RowBounds pagination to perform count query.

The
default value of pageSizeZero is false. When this parameter is set to true, all results will be queried if pageSize=0 or RowBounds.limit =0 (equivalent to no page query, but the returned result is still Page type).

Reasonable
paging rationalization parameter, the default value is false. When this parameter is set to true, the first
page will be queried when pageNum<=0, and the last page will be queried when pageNum>pages (when the total number is exceeded). When the default is false, query directly based on the parameters.

params
To support startPage (Object params) method, which increases the parameter configuration parameter mapping for the object according to attributes
of the name argument can be configured pageNum, pageSize, count, pageSizeZero, reasonable, not configured with default values mapped , The default value is
pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero

Use of paging plugin

The use of the paging plug-in is very simple. After configuration, you can directly call the static method startPage of PageHelper to realize paging. Other queries can be written normally. Note that the method of calling startPage must be written before the query selectAll(), otherwise paging invalid.

/**
 * 分页测试
 */
@Test
public void testPage(){
    
    

    //page 当前页    size 每页显示多少条
    int page = 1,size=10;
    //分页处理,只需要调用PageHelper.startPage静态方法即可。

    PageHelper.startPage(page,size);                       
    //必须写在要真正执行的代码之前
  //startPage的方法必须写在执行查询selectAll()前面 

//查询
    List<Brand> brands = brandMapper.selectAll();
//获取分页信息,注意这里传入了brands集合对象

    PageInfo<Brand> pageInfo = new PageInfo<Brand>(brands);
    System.out.println(pageInfo);
}

Examples are as follows

aside.jsp
aside.jsp

<li id="system-setting"><a
	href="${pageContext.request.contextPath}/orders/findAll.do?page=1&size=4"> <i
			class="fa fa-circle-o"></i> 订单管理
	</a></li>

OrdersController.java contoller layer

Controller
@RequestMapping("/orders")
public class OrdersController {
    
    
    @Autowired
    private IOrdersService ordersService;
    //查询全部订单---未分页
//    @RequestMapping("/findAll.do")
//    public ModelAndView findAll() throws Exception {
    
    
//        ModelAndView mv = new ModelAndView();
//        List<Orders> ordersList = ordersService.findAll();
//        mv.addObject("ordersList", ordersList);
//        mv.setViewName("orders-list");
//        return mv;
//    }
    @RequestMapping("/findAll.do")
    //注意该默认的参数
    public ModelAndView findAll(@RequestParam(name = "page", required = true, defaultValue = "1") int page, @RequestParam(name = "size", required = true, defaultValue = "4") int size) throws Exception {
    
    
        ModelAndView mv = new ModelAndView();

        List<Orders> ordersList = ordersService.findAll(page, size);
        
		//PageInfo就是一个分页Bean    重新封装
        PageInfo pageInfo=new PageInfo(ordersList);
        mv.addObject("pageInfo",pageInfo);

              //通过modelAndview跳转到相关界面
        mv.setViewName("orders-page-list");
        return mv;
    }
}

service layer

@Service
@Transactional
public class OrdersServiceImpl implements IOrdersService {
    
    
    @Autowired
    private IOrdersDao ordersDao;
    @Override
    public List<Orders> findAll(int page, int size) throws Exception {
    
    
        //参数pageNum 是页码值   参数pageSize 代表是每页显示条数
                     //必须写在要真正执行的代码之前
        PageHelper.startPage(page, size);
        return ordersDao.findAll();
    }
}

The front-end interface displayed when the data is returned is:
orders-page-list.jsp

<tbody>
									<c:forEach items="${pageInfo.list}" var="orders">
										<tr>
											<td><input name="ids" type="checkbox"></td>
											<td>${orders.id }</td>
											<td>${orders.orderNum }</td>
											<td>${orders.product.productName }</td>
											<td>${orders.product.productPrice }</td>
											<td>${orders.orderTimeStr }</td>
											<td class="text-center">${orders.orderStatusStr }</td>
											<td class="text-center">
												<button type="button" class="btn bg-olive btn-xs">订单</button>
												<button type="button" class="btn bg-olive btn-xs" onclick="location.href='${pageContext.request.contextPath}/orders/findById.do?id=${orders.id}'">详情</button>
												<button type="button" class="btn bg-olive btn-xs">编辑</button>
											</td>
										</tr>
									</c:forEach>
								</tbody>

```xml

                    

Pay attention to the fact that PageInfo has already encapsulated a lot of information for us, such as the total number of pages, the total number of entries, the current page, etc.
Pay attention to the writing of this page number

<div class="pull-left">
                        <div class="form-group form-inline">
                            总共2 页,共14 条数据。 每页		
                            	
<!--注意onchange函数  选了某一个就会去调用相关函数-->
                            <select class="form-control" id="changePageSize" onchange="changePageSize()">
                                <option>1</option>
                                <option>2</option>
                                <option>3</option>
                                <option>4</option>
                                <option>5</option>
                            </select></div>
                    </div>

                    <div class="box-tools pull-right">
                        <ul class="pagination">
                            <li>
                             <!--重点注意${pageInfo.pageSize}动态获取-->
                                <a href="${pageContext.request.contextPath}/orders/findAll.do?page=1&size=${pageInfo.pageSize}" aria-label="Previous">首页</a>
                            </li>
                            <li>
 <!--重点注意pageInfo.pageNum  表示当前页-->
           <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标签-->					   
			<a href="${pageContext.request.contextPath}/orders/findAll.do?page=${pageNum}&size=${pageInfo.pageSize}">${pageNum}
							   </a></li>
						   </c:forEach>
<!--重点注意pageInfo.pageNum  表示当前页-->
                            <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>



<!--重点注意此function方法-->
function changePageSize() {
	//获取下拉框的值
	//会根据id获取到相应的值
	var pageSize = $("#changePageSize").val();

	//向服务器发送请求,改变没页显示条数
	location.href = "${pageContext.request.contextPath}/orders/findAll.do?page=1&size="
			+ pageSize;
}

Guess you like

Origin blog.csdn.net/Liamcsl/article/details/113974843