Day29 SSM之CRUD pagehelper

**源码地址:**https://github.com/BigAnt-cyl/ssm_zhenghe_shili_ajax_bootstrap

pagehelper分页插件介绍

  • (1)pagehelper是什么?
    针对Mybatis提供分页插件,将分页查询简化
  • (2)依赖配置 pagehelper
  • (3)配置插件 plugin
    配置方法有两种
    》1 : 在mybatis核心配置文件中配置,在applicationContext.xml中引入 mybatis核心配置文件
    》2 : 在applicationContext.xml中配置

pom.xml

    <!--引入pageHelper分页插件 -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.0.0</version>
    </dependency>

配置方式1:SqlMapConfig.xml中配置

    <!--
    参数合理化
              如果当前currPage < 1  则按currPage = 1查询
              如果当前currPage > totalPage  则按currPage = totalPage 查询
     -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
                <property name="reasonable" value="true"/>
        </plugin>
    </plugins>

注意还需要在applicationContext.xml中指定SqlMapConfig.xml的位置

    <!-- 配置 MyBatis 的 Session 工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!--起别名-->
        <property name="typeAliasesPackage" value="cn.cyl.domain"/>
        <property name="configLocation" value="classpath:SqlMapConfig.xml"/>
    </bean>

配置方式2:applicationContext.xml中配置

<!-- 配置 MyBatis 的 Session 工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!--起别名-->
        <property name="typeAliasesPackage" value="cn.cyl.domain"/>
        <!--引用mybatis文件-->
        <!--<property name="configLocation" value="classpath:SqlMapConfig.xml"/>-->

        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <!--使用下面的方式配置参数,一行配置一个 -->
                        <value>
                            <!--参数合理化
                    如果当前currPage < 1  则按currPage = 1查询
                    如果当前currPage > totalPage(总页数)  则按currPage = totalPage 查询-->
                            reasonable=true
                            <!-- 指定数据库方言 -->
                            helperDialect=mysql
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

原理 在拦截器

先调用 PageHelper.startPage(1,10) 再调用全查,才能自动分页

	//给定分页参数
	//PageHelper.startPage(currentPage,pageSize)
    PageHelper.startPage(1,10);//参1:当前页 参2 每页记录数
    //一个全查,其他都交给PageInterceptor
    List<Department> list = iDepartmentService.findAllDepartments();

其原理就是我们写好一个全查语句,拦截器 PageInterceptor 拦截后使用全查语句拼接limit分页,所以每个sql最后 建议不要写分号;

select * from department

它会帮我们拼接

select * from department limit (currentPage-1)*pageSize,pageSize;
# 第一页
select * from department limit 0, 10 ;

然后还帮我们查总数

select count(*) from department

示例1:JSP加SSM

后台代码

src\main\java\cn\cyl\controller\DepartmentV3Controller.java

	@RequestMapping(path="/pageUI",method = RequestMethod.GET)
    public String page(Model model, Integer currPage, Integer pageSize){//你需要第几页数据,每页数据多条
        log.info("page currPage="+currPage);
        log.info("page pageSize="+pageSize);

        if(currPage==null){
            currPage=1;
        }
        if (pageSize==null){
            pageSize=5;
        }

        //给定分页参数
        PageHelper.startPage(currPage,pageSize);
        //一个全查,其他都交给PageInterceptor
        List<Department> list = iDepartmentService.findAllDepartments();
		//拿取完整分页数据
		//PageInfo{pageNum=1, pageSize=3, size=3, startRow=1, endRow=3, total=13, pages=5, list=Page{count=true, pageNum=1, pageSize=3, startRow=0, endRow=3, total=13, pages=5, reasonable=true, pageSizeZero=false}
		//[Student(id=1, name=ls, age=121), Student(id=2, name=fdasf, age=121), Student(id=3, name=ls, age=121), Student(id=4, name=lfs, age=121), Student(id=5, name=rls, age=121)], 
		//prePage=0, nextPage=2, isFirstPage=true, isLastPage=false, hasPreviousPage=false, hasNextPage=true, navigatePages=8, navigateFirstPage=1, navigateLastPage=5, navigatepageNums=[1, 2, 3, 4, 5]}
        PageInfo<Department> pi = new PageInfo<>(list);

        model.addAttribute("pi",pi);
        return "list_v3";
    }

前台代码

导入c标签 使用里面的foreach与if标签
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

src\main\webapp\WEB-INF\pages\list_v3.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <meta charset="utf-8">
    <!--兼容IE浏览器-->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!--兼容手机-->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
    <% pageContext.setAttribute("path",request.getContextPath()); %>
    <!-- Bootstrap -->
    <link href="${path}/css/bootstrap.min.css" rel="stylesheet">
    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
    <script src="${path}/js/jquery-1.11.0.min.js"></script>
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script src="${path}/js/bootstrap.min.js"></script>
    <title>部门列表</title>
</head>
<body>
<%--${pi}--%>
<!--container表示容器,所有内容放进这个容器-->
<div class="container" >
    <!-- row表示 一行的宽度-->
    <div class="row">
        <!--col-md-4 表示使用一行的4/12宽度 -->
        <div class="col-md-4" >
            <h1>部门列表</h1>
        </div>
    </div>
    <div class="row">
        <!--占四格,并向左移八格-->
        <div class="col-md-4 col-md-offset-8" >
            <button class="btn btn-primary"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> 新增</button>
        </div>
    </div>
    <%--循环列表的行--%>
    <div class="row">
        <div class="col-md-12" >
            <table class="table table-hover">
                <tr >
                    <th >部门编号</th>
                    <th ></th>
                    <th >部门名称</th>
                    <th >操作</th>
                </tr>
                <c:forEach items="${pi.list}" var="dept">
                    <tr>
                        <td>${dept.did}</td>
                        <td></td>
                        <td>${dept.dname}</td>
                        <td>
                            <button class="btn btn-danger"> <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> 删除</button>/
                            <button class="btn btn-info"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> 修改</button>
                        </td>
                    </tr>
                </c:forEach>
            </table>
        </div>
    </div>
    <%--赋值显示分页工具条--%>
    <div class="row">
        <div class="col-md-6" >当前共有${pi.total}条记录,共${pi.pages}页</div>
        <div class="col-md-6" >
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    <li>
                        <a href="#" aria-label="Previous">
                            <span aria-hidden="true">首页</span>
                        </a>
                    </li>
                    <!--如果有上一页-->
                    <c:if test="${pi.hasPreviousPage}">
                        <li>
                            <a href="#" aria-label="Previous">
                                <span aria-hidden="true">上一页</span>
                            </a>
                        </li>
                    </c:if>

                    <c:forEach items="${pi.navigatepageNums}" var="num">
                        <!--如果当前页,就显示高亮-->
                        <c:if test="${num == pi.pageNum}">
                            <li class="active"><a href="#">${num}</a></li>
                        </c:if>
                        <c:if test="${num != pi.pageNum}">
                            <li><a href="#">${num}</a> </li>
                        </c:if>
                    </c:forEach>
                    <!--如果有下一页-->
                    <c:if test="${pi.hasNextPage}">
                        <li>
                            <a href="#" aria-label="Next">
                                <span aria-hidden="true">下一页</span>
                            </a>
                        </li>
                    </c:if>
                    <li>
                        <a href="#" aria-label="Previous">
                            <span aria-hidden="true">末页</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    </div>
</div>

</body>
</html>

数据库信息

在这里插入图片描述

运行结果

在这里插入图片描述

示例二:前台elementUI+vue后台SSM

前台

<template>
	<!-- 
	此处使用了ElementUI的Pagination分页组件
	
	@size-change="handleSizeChange"
	    绑定函数,当每页记录数更改时激发,自动传递每页记录数的值
	@current-change="handleCurrentChange"
	    绑定函数,当当前页更改时激发,自动传递当前页的值
	
	:current-page:绑定当前第几页
	:page-sizes:绑定每页记录数改动幅度,即每页显示个数选择器的选项设置
	:page-size:绑定每页记录数,即显示的个数
	:total:绑定总记录数
	layout="total, sizes, prev, pager, next, jumper"
	分页布局,此处共设置了六个组件
	-->
	<el-pagination class="bottom"
	@size-change="handleSizeChange"
	@current-change="handleCurrentChange"
	:current-page="params.pageNumber"
	:page-sizes="[1, 2, 3, 4]"
	:page-size="params.pageSize"
	layout="total, sizes, prev, pager, next, jumper"
	:total="total">
	</el-pagination>
</template>
<script>
export default {
    data(){
        return{
			total:0,
			start:'',
			list:[],
			params:{
				pageNumber:1,
				pageSize:2,
				name:'',   
				stuno:'',   
				startdate:'',    
				svo:[],
			}
        },
    },
    methods:{
	     // v:每页条数,pageSize
        /* val是更改后的每页记录数 */
        handleSizeChange(val){
            this.params.pageSize = val 
            //改变每页条数后重新查询
            this.queryStu()()
        },
        // val:当前页,pageNumber
        handleCurrentChange(val){
            this.params.pageNumber = val 
            //改变页码后重新查询
            this.queryStu()
        },
        queryStu(){
            this.$http.post('/stu/queryStu',this.params).then(resp=>{
                console.log(resp)
                //对象数据
                this.list = resp.data.data.list
                //总数
                this.total = resp.data.data.total
                //startRow为后台返回的分页数据的第几条,
                //此处-1是为了上面表格序号calcIndex(v)的计算,酌情考虑减不减
                this.start = resp.data.data.startRow-1
            })
		}
	}
}

后台

    @PostMapping("/queryStu")
    public JsonResponse queryStu(@RequestBody ConditionVo vo){
            //给定分页参数
        PageHelper.startPage(vo.getPageNumber(),vo.getPageSize());
        List<Student> data = studentService.queryStu(map);
        PageInfo<Student> pi = new PageInfo<>(data);
        return ResultStatus.suc(pi);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值