zoukankan      html  css  js  c++  java
  • Pagehelper 分页插件使用

    1.使用maven导入jar包

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

     2.在mybatis-config.xml中添加如下配置:

     <!-- 配置分页插件 -->
        <plugins>
            <plugin interceptor="com.github.pagehelper.PageInterceptor">
            
            </plugin>
        </plugins> 
    

     分页插件版本不同,interceptor 可能会有区别,配置方式根据实际情况配置参数

    3.Service层 使用分页插件

    Page page = PageHelper.startPage(pageNum,sizeNum,count);
    List<MainSearchVo> mainSearchVoList = companyMainPageMapper.getMainSearch(fname);
    

    参数详解:

    pageNum:当前页

    sizeNum:每页显示条数

    count :是否查询总条数 (true:查询 ,false:不查询)

    获取总页数:  page.getPages()

    4.什么时候会导致不安全的分页?

    PageHelper 方法使用了静态的 ThreadLocal 参数,分页参数和线程是绑定的。
    
    只要你可以保证在 PageHelper 方法调用后紧跟 MyBatis 查询方法,这就是安全的。因为 PageHelper 在 finally 代码段中自动清除了 ThreadLocal 存储的对象。
    
    如果代码在进入 Executor 前发生异常,就会导致线程不可用,这属于人为的 Bug(例如接口方法和 XML 中的不匹配,导致找不到 MappedStatement 时), 这种情况由于线程不可用,也不会导致 ThreadLocal 参数被错误的使用。
    
    但是如果你写出下面这样的代码,就是不安全的用法:
    
    PageHelper.startPage(1, 10);
    List<Country> list;
    if(param1 != null){
        list = countryMapper.selectIf(param1);
    } else {
        list = new ArrayList<Country>();
    }
    这种情况下由于 param1 存在 null 的情况,就会导致 PageHelper 生产了一个分页参数,但是没有被消费,这个参数就会一直保留在这个线程上。当这个线程再次被使用时,就可能导致不该分页的方法去消费这个分页参数,这就产生了莫名其妙的分页。
    
    上面这个代码,应该写成下面这个样子:
    
    List<Country> list;
    if(param1 != null){
        PageHelper.startPage(1, 10);
        list = countryMapper.selectIf(param1);
    } else {
        list = new ArrayList<Country>();
    }
    这种写法就能保证安全。
  • 相关阅读:
    php 日期处理 DateTime
    http范围请求
    fiddle扩展
    汉字编码 (GB2312 GBK GB18030)
    Navicat http 通道增加验证
    vim 支持 nginx配置文件 语法高亮
    composer 使用
    剖析nsq消息队列(三) 消息传输的可靠性和持久化[一]
    剖析nsq消息队列(二) 去中心化源码解析
    剖析nsq消息队列(一) 简介及去中心化实现原理
  • 原文地址:https://www.cnblogs.com/lin-mumu/p/10921983.html
Copyright © 2011-2022 走看看