mybatis分页插件实现分页

本文介绍如何使用MyBatis分页插件PageHelper实现数据库查询分页功能,包括配置依赖、添加拦截器及编写DAO层等步骤,并提供了一个完整的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.了解过程:在数据库服务器中,sql语句实现分页便要每个查询语句都要写上limit(开始,结束),并且不能灵活的随前端变化,为此使用拦截器的方法,过程:拦截器拦截请求的sql语句(根据需要拦截的ID(正则匹配),进行拦截),并对根据前端传过来的页数,和每页的条数,计算出limit(开始,结束),总条数,然后,拼接到sql语句后边。其中这个处理过程,已经封装到了,分页插件中,可以不用理解,直接使用。
条件:maven下:
1.pom.xml中导入依赖:

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

2.在mybatis-conf.xml中添加拦截器:

<plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->        
            <property name="dialect" value="mysql"/>
        </plugin>
    </plugins>

3.编写page实例:

package com.tc.tccp.core.page;

/** 
 * @author wangpei 
 * @version 
 *创建时间:2016年10月12日 下午10:52:29 
 * 拦截器实现mybatis的拦截
 */
import java.util.List;

public class PageParameter {

    public static final int DEFAULT_PAGE_SIZE = 10;

    private int pageSize;// 页面大小
    private int currentPage;// 当前页的位置
    private int prePage;// 上一页
    private int nextPage;// 下一页
    private int totalPage;// 总页数
    private int totalCount;// 总条数
    /**
     * 当前页的数据
     */
    private List<?> list;

    /**
     * 获得分页内容
     *
     * @return
     */
    public List<?> getList() {
        return list;
    }

    public PageParameter(int pageSize, int currentPage, int prePage,
            int nextPage, int totalPage, int totalCount, List<?> list) {
        this.pageSize = pageSize;
        this.currentPage = currentPage;
        this.prePage = prePage;
        this.nextPage = nextPage;
        this.totalPage = totalPage;
        this.totalCount = totalCount;
        this.list = list;
    }

    /**
     * 设置分页内容
     *
     * @param list
     */
    @SuppressWarnings("unchecked")
    public void setList(List list) {
        this.list = list;
    }

    public PageParameter() {
        this.currentPage = 1;
        this.pageSize = DEFAULT_PAGE_SIZE;
    }

    /**
     *
     * @param currentPage
     * @param pageSize
     */
    public PageParameter(int currentPage, int pageSize) {
        this.currentPage = currentPage;
        this.pageSize = pageSize;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

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

    public int getPrePage() {
        return prePage;
    }

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

    public int getNextPage() {
        return nextPage;
    }

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

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public String toString() {
        return "pageSize=" + pageSize + "currentPage=" + currentPage
                + "prePage=" + prePage + "nextPage=" + nextPage + "totalPage="
                + totalPage + "totalCount=" + totalCount;
    }

}

4.编写操做的dao层,和dao.xml
其中,需要拦截的方法,需要以ID(正则匹配),我以.page结尾。
这里写图片描述
5.controller层

    @RequestMapping("getAll")
    @ResponseBody
    public Map<String, Object> get(HttpServletRequest request,HttpServletResponse response, Integer page/* 当前页 */, Integer rows/* 每页显示的数量 */) {
        // 当前页
        int intPage = page == null ||  page <= 0 ? 1 : page;
        // 设置每页显示的数量
        int intPageSize = rows == null || rows <= 0 ? 10 : rows;
        PageParameter page1 = new PageParameter();
        System.out.println("当前页="+intPage);
        System.out.println("一页的条数="+intPageSize);
        page1.setCurrentPage(intPage);
        page1.setPageSize(intPageSize);
        PageHelper.startPage(intPage, intPageSize);
        List<Studio> d = studioService.findAllStudioByPage(page1); // 取商品列表
        PageInfo<Studio> pageInfo = new PageInfo<Studio>(d);
        Map<String, Object> reMap = new HashMap<String, Object>();
        // 取分页信息
        reMap.put("total", pageInfo.getTotal()); // 总条数
        reMap.put("pageSize", intPageSize); // 每页显示的数量
        reMap.put("pageNo", intPage); // 当前页数
        reMap.put("rows", d); // 从数据库中获取的列表信息

        return reMap;
    }

将获取到的查新结果放入reMap,然后前端获取到reMap的值,类似json格式的数据。

前端jsp页面自己完成,我是用easyui做的,

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    //System.out.println("path===" + path);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>LayOut</title>
 <script src="<%=request.getContextPath()%>/css/easyui/jquery.min.js" type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/css/easyui/jquery.easyui.min.js" type="text/javascript"></script>
<link href="<%=request.getContextPath()%>/css/easyui/themes/default/easyui.css" rel="stylesheet"ntype="text/css" />
<link href="<%=request.getContextPath()%>/css/easyui/themes/icon.css" rel="stylesheet" type="text/css" /> 
<script type="text/javascript">
    $(function() {
    $('#dg').datagrid({
            title : '结果列表',
            pageSize : 10,//默认选择的分页是每页10行数据
            pageList : [ 5, 10, 15, 20 ],//可以选择的分页集合
            nowrap : true,//设置为true,当数据长度超出列宽时将会自动截取
            striped : true,//设置为true将交替显示行背景。
            collapsible : true,//显示可折叠按钮

            url : '/tccp/studio/getAll',//url调用Action方法
            loadMsg : '数据装载中......',
            singleSelect : false,//为true时只能选择单行
            fitColumns : false,
            remoteSort : false,
            onClickRow : function(rowIndex, rowData) {//单击事件
            },
            onDblClickRow : function(rowIndex, rowData) {//双击事件
            },

            toolbar : [ {// 工具栏  
                text : '添加',  
                iconCls : 'icon-add', // 图标  
                handler : function() { // 处理函数  
                    addBook();  
                }  
            }, {  
                text : '删除',  
                iconCls : 'icon-cancel', // 图标  
                handler : function() { // 处理函数  
                    deleteBook();  
                }  
            }, {  
                text : '编辑',  
                iconCls : 'icon-edit',// 图标  
                handler : function() {// 处理函数  
                    editBook();  
                }  
            } ],  

            frozenColumns : [ [ {
                field : 'id',
                checkbox : true
            },  {
                field : 'studio_id',
                align : 'center',
                title : '厅号',
                width : 200
            }, {
                field : 'studio_name',
                align : 'center',
                title : '厅名',
                width : 200
            } ] ],
            columns : [ [ {
                field : 'studio_row_count',
                align : 'center',
                title : '行数',
                width : 200
            }, {
                field : 'studio_col_count',
                align : 'center',
                title : '列数',
                width : 200
            },{
                field : 'studio_introduction',
                align : 'center',
                title : '介绍',
                width : 200
            },{
                field : 'studio_flag',
                align : 'center',
                title : '是否安排座位',
                width : 220
            }] ],
            pagination : true,//分页
            rownumbers : true
        //行数
        });
        var p = $('#dg').datagrid('getPager');  

        $(p).pagination({  
            pageSize: 10,//每页显示的记录条数,默认为10   
            pageList: [5,10,15,20],//可以设置每页记录条数的列表   
            beforePageText: '第',//页数文本框前显示的汉字   
            afterPageText: '页    共 {pages} 页',   
            displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录',   
        });


        //在datagrid实例化之后调用这个方法。
        $("#dg").datagrid({}).datagrid("page");

    });




    function showEditForm() {  

            $('#EditForm').form('submit', {
                url: "/tccp/studio/add",
                onSubmit: function () {               //表单提交前的回调函数
                    var isValid = $(this).form('validate');//验证表单中的一些控件的值是否填写正确,比如某些文本框中的内容必须是数字
                    if (!isValid) {
                    }
                    return isValid; // 如果验证不通过,返回false终止表单提交
                },
                success: function (data) {    //表单提交成功后的回调函数,里面参数data是我们调用/BasicClass/ModifyClassInfo方法的返回值。
                    if (data > 0) {
                        $.messager.show({
                            title: '提示消息',
                            msg: '提交成功',
                            showType: 'show',
                            timeout: 1000,
                            style: {
                                right: '',
                                bottom: ''
                            }
                        });
                        $('#dg').datagrid('reload');    // 重新载入当前页面数据  
                        $('#Editwin').window('close');  //关闭窗口
                    }
                    else {
                        $.messager.alert('提示信息', '提交失败,请联系管理员!', 'warning');
                }
                }
            });
    }  

    // 关闭窗口  
    function closeForm() {  
        $("#frmEdit").form('clear');  
        $('#tabEdit').dialog('close');  
    }  
    // 添加的函数  
    function addBook() {  
        // 清空原有的数据  
        $('#frmEdit').form('clear');  
        // 显示添加对话框  
        showEditForm();  
    }  


</script>
</head>

<body class="easyui-layout" id="cc">

   <div id="tabEdit">  
                    <form id="frmEdit">  
                    <input type="hidden" id="id" name="book.id" />  
                    <dl>  
                        <dd>  
                            演出厅编号:  
                        </dd>  
                        <dd>  
                            <input type="text" style="width: 150px" id="isbn" name="studioId" />  
                        </dd>  
                    </dl>  
                    <dl>  
                        <dd>  
                            演出厅名称:  
                        </dd>  
                        <dd>  
                            <input type="text" style="width: 150px" id="title" name="studioName" />  
                        </dd>  
                    </dl>  
                    <dl>  
                        <dd>  
                            演出厅行号:  
                        </dd>  
                        <dd>  
                            <input type="text" style="width: 150px" id="price" name="studioRow" />  
                        </dd>  
                    </dl>  
                    <dl>  
                        <dd>  
                            演出厅列号:  
                        </dd>  
                        <dd>  
                            <input type="text" style="width: 150px" id="pubdate" name="studioCol" />  
                        </dd>  
                    </dl>  
                    <dl>  
                        <dd>  
                            是否安排座位:  
                        </dd>  
                        <dd>  
                            <input type="text" style="width: 150px" id="pubdate" name="flag" />  
                        </dd>  
                    </dl>  
                    <dl>  
                        <dd>  
                            演出厅介绍:  
                        </dd>  
                        <dd>  
                            <textarea cols="45" rows="3" id="intro" name="studioIntroduce"></textarea>  
                        </dd>  
                    </dl>  
                    </form>  
                </div>  

<div region="north" border="true" split="true"
        style="overflow: hidden; height: 65px;">
        <form id="searchForm" name="searchForm">
            <table id="searchTable" width=100%>
                <tr>    
                    <td>当前位置:<a href="javascript:void(0)" style="color:#6E6E6E;">影厅管理</a> &gt; 内容列表<!--   <input class="easyui-textbox" type="text" name="bh"  id="bh">--></td>
                            &nbsp;&nbsp;&nbsp;      
                    <td>厅名:<input class="easyui-textbox" type="text" name="bjmc" id="bjmc">&nbsp;<a href="#" class="easyui-linkbutton" icon="icon-search"
                        onclick="doSearch()">查询</a>
                    </td>
                    <td>
                    &nbsp;&nbsp;&nbsp;  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  
                      <td><a href="#" class="easyui-linkbutton" icon="icon-search"
                        onclick="doSearch()">退出</a>
                    </td>                       
                </tr>
            </table>

        </form>
    </div>
    <div region="center" border="true" split="true"
        style="overflow: hidden;">
        <table id="dg" title="My Users" class="easyui-datagrid" width="100%"
            height="99%" toolbar="#toolbar" rownumbers="true" fitColumns="true"
            singleSelect="true">

        </table>


    </div>





</body>
</html>

代码写的有点乱,我会继续改的,原谅小白一枚!!!!,有什么问题就问,要源码的,都可以。

<think>我们正在讨论MyBatis分页插件PageHelper的使用方法。根据引用内容,我们可以总结出以下步骤: 1. 引入依赖(Maven项目) 2. 配置分页插件(在MyBatis配置文件中或Spring Boot配置文件中) 3. 在代码中使用PageHelper.startPage方法启动分页 4. 执行查询 5. 使用PageInfo对结果进行包装 下面我们按照这些步骤详细说明。 ### 1. 引入依赖 在Maven项目的pom.xml中添加PageHelper依赖: ```xml <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.3.0</version> <!-- 使用最新版本 --> </dependency> ``` ### 2. 配置分页插件 配置方式有两种:在MyBatis的配置文件(如mybatis-config.xml)中配置,或者在Spring Boot的配置文件中配置(如application.yml)。 **MyBatis配置文件方式(mybatis-config.xml)**: ```xml <configuration> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- 配置数据库方言,例如mysql --> <property name="helperDialect" value="mysql"/> <!-- 其他配置 --> </plugin> </plugins> </configuration> ``` **Spring Boot配置方式(application.yml)**: ```yaml pagehelper: helper-dialect: mysql # 数据库方言 reasonable: true # 分页合理化 support-methods-arguments: true # 支持方法参数传递分页参数 ``` ### 3. 在代码中使用分页 在需要分页的查询方法前调用`PageHelper.startPage`方法,然后执行查询。注意:`PageHelper.startPage`方法后的第一个查询方法会被分页。 例如: ```java // 在Service层或Controller层 public PageInfo<Emp> getEmpsByPage(int pageNum, int pageSize) { // 开始分页,pageNum: 当前页码,pageSize: 每页显示数量 PageHelper.startPage(pageNum, pageSize); // 紧接着的查询会被分页 List<Emp> list = empDao.selectAll(); // 使用PageInfo包装查询结果,PageInfo包含了分页的详细信息 PageInfo<Emp> pageInfo = new PageInfo<>(list); return pageInfo; } ``` ### 4. PageInfo对象 `PageInfo`对象包含了分页后的各种信息,如当前页、总页数、总记录数、是否有上一页下一页等。常用属性如下: - `pageNum`:当前页码 - `pageSize`:每页数量 - `total`:总记录数 - `pages`:总页数 - `list`:当前页的数据列表 ### 注意事项 - `PageHelper.startPage`方法要紧跟查询语句,中间不能有其他逻辑,否则可能导致分页失败。 - 如果查询结果为空,`PageInfo`对象中的属性也会被正确设置(如总记录数为0)。 - 支持多种数据库,通过配置`helperDialect`指定数据库方言。 ### 示例代码 假设有一个EmpDao接口,其中有一个查询所有员工的方法`selectAll`: ```java public interface EmpDao { List<Emp> selectAll(); } ``` 在Service层实现分页查询: ```java @Service public class EmpService { @Autowired private EmpDao empDao; public PageInfo<Emp> getEmpPage(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); List<Emp> emps = empDao.selectAll(); return new PageInfo<>(emps); } } ``` 在Controller层调用: ```java @RestController public class EmpController { @Autowired private EmpService empService; @GetMapping("/emps") public PageInfo<Emp> listEmps(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) { return empService.getEmpPage(pageNum, pageSize); } } ``` 这样,当访问`/emps?pageNum=1&pageSize=10`时,就会返回第一页的10条员工数据,并且包含分页信息。 ### 总结 使用PageHelper实现分页查询的步骤是:引入依赖、配置插件、在查询前调用`PageHelper.startPage`、使用`PageInfo`包装结果。这种方法简单且对原有代码侵入小,是MyBatis分页的常用解决方案[^1][^2][^3]。 §§相关问题§§ 1. PageHelper分页插件支持哪些数据库? 2. 如何配置PageHelper以实现多数据源分页? 3. PageHelper的分页原理是什么? 4. 在使用PageHelper时常见的错误有哪些?如何解决?</think>### MyBatis 分页插件 PageHelper 使用指南 #### 1. **引入依赖** 在 Maven 项目的 `pom.xml` 中添加依赖: ```xml <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.3.2</version> <!-- 使用最新版本 --> </dependency> ``` #### 2. **配置插件** **Spring Boot 配置(application.yml)**: ```yaml pagehelper: helper-dialect: mysql # 指定数据库类型(mysql/oracle等) reasonable: true # 分页合理化(页码超出范围时自动调整) support-methods-arguments: true # 支持通过方法参数传递分页 params: count=countSql # 优化COUNT查询 ``` **传统 MyBatis 配置(mybatis-config.xml)**: ```xml <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <property name="helperDialect" value="mysql"/> </plugin> </plugins> ``` #### 3. **基础分页查询** 在 Service 或 Controller 层实现分页: ```java // 示例:查询第2页,每页10条数据 public PageInfo<Emp> getEmpPage(int pageNum, int pageSize) { // 1. 启动分页 PageHelper.startPage(pageNum, pageSize); // 2. 执行原始查询(无需修改SQL) List<Emp> emps = empDao.selectAll(); // 普通查询方法 // 3. 封装分页结果(包含页码/总条数等元数据) return new PageInfo<>(emps); } ``` #### 4. **前端参数传递** Controller 接收分页参数: ```java @GetMapping("/emps") public PageInfo<Emp> list( @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize ) { return empService.getEmpPage(pageNum, pageSize); } ``` #### 5. **PageInfo 核心属性** 分页结果对象包含: ```java pageInfo.getList(); // 当前页数据列表 pageInfo.getPageNum(); // 当前页码 pageInfo.getPageSize(); // 每页条数 pageInfo.getTotal(); // 总记录数 pageInfo.getPages(); // 总页数 pageInfo.isHasNextPage();// 是否有下一页 ``` #### 6. **高级用法** **参数分页**(方法参数传递): ```java // Dao层接口 List<Emp> selectByCondition( @Param("name") String name, @Param("pageNum") int pageNum, @Param("pageSize") int pageSize ); // Service调用(无需PageHelper.startPage) PageInfo<Emp> page = new PageInfo<>( empDao.selectByCondition("张三", 1, 10) ); ``` **多数据源配置**: ```yaml # 指定不同Mapper使用不同方言 pagehelper: auto-dialect-class: com.example.CustomDialect ``` ### 注意事项 1. `PageHelper.startPage()` 必须紧邻 **查询语句之前**,中间不可插入其他逻辑。 2. 返回的 `PageInfo` 对象可序列化为 JSON 直接返给前端。 3. 复杂关联查询时,确保 `COUNT` 语句性能(可自定义 `countColumn` 优化)[^3]。 > 示例:查询结果包含分页元数据 > ```json > { > "pageNum": 1, > "pageSize": 10, > "total": 85, > "pages": 9, > "list": [ ... ] // 当前页数据 > } > ``` 通过 PageHelper 可显著简化分页开发,避免手动编写 `LIMIT/OFFSET` 和 `COUNT` 查询[^1][^2]。 --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值