美文网首页
Mybatis 分页插件 PageHepler

Mybatis 分页插件 PageHepler

作者: tingshuo123 | 来源:发表于2018-08-14 21:18 被阅读45次

    常用的分页类型:

    • 物理分页依赖的是某一物理实体,这个物理实体就是数据库,比如MySQL数据库提供了limit关键字,直接查询出分页数据。

    • 逻辑分页依赖的是程序员编写的代码。查询数据库获取所有结果,存储在内存中,然后再由通过代码获取分页数据。

    PageHelper 采用的是物理分页

    想要使用 PageHelper 需要引入两个 jar 包,jsqlparser-1.0.jarpagehelper-5.1.4.jar

    也可以使用 Maven 在 pom.xml 中添加以下依赖:

    <dependency>
       <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <-- 版本号 -->
        <version>5.1.4</version>
    </dependency>
    

    在 mybatis 的配置文件中 添加

        <!-- 配置插件 -->
        <plugins>
    
            <!-- 配置分页插件 -->
            <plugin interceptor="com.github.pagehelper.PageInterceptor">
                <!-- 指定方言 -->
                <property name="helperDialect" value="mysql" />
                <!-- 分页合理化,page超过总页数时,显示最后一页 -->
                <property name="reasonable" value="true"/>
            </plugin>
    
        </plugins>
    

    使用就是在正常查询之前添加PageHelper.startPage(page, count);page 表示当前页数,count 每页展示的数据数量。

    使用示例:

        @Select("select u_id as id, u_name as name, u_pwd as pwd from t_user3")
        public List<UserBean> findAll();
    
        @Test
        public void test02() {
            
            ApplicationContext contxt = new ClassPathXmlApplicationContext("config/springConfig.xml");
            
            // 第一个参数表示第几页,第二个参数表示每页显示多少条记录
            PageHelper.startPage(3, 30);
            // PageHelper.startPage 后面的第一次查询语句会执行分页
            IUserDao dao = (IUserDao) contxt.getBean("IUserDao");
            List<UserBean> list = dao.findAll();
            
            for (UserBean userBean : list) {
                System.out.println(userBean);
            }
        }
    

    注意: 只有 PageHelper.startPage 后面的第一次查询语句会执行分页,所以最好 查询语句紧跟 PageHelper.startPage 的下一行。

    相关文章

      网友评论

          本文标题:Mybatis 分页插件 PageHepler

          本文链接:https://www.haomeiwen.com/subject/qvrbbftx.html