插件官方文档地址:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md
使用方法:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md
PageHelper是一款好用的开源免费的Mybatis第三方物理分页插件
1、pom.xml 引入 pagehelper 依赖
<!-- pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.4</version>
</dependency>
2、在Mybatis中全局配置文件中配置拦截器
<!-- 在environments标签的前面 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
<property name="helperDialect" value="mysql"/>
</plugin>
</plugins>
3、sql映射文件
public List<User> selectUserBylike(@Param("username") String username,
@Param("state") Integer state);
<select id="selectUserBylike" resultType="cn.jq.mybatis.model.User">
select
<include refid="Base_Column_List" />
from t_user
<where>
<if test="username != null and username != ''">
and username like concat('%',concat(#{username},'%'))
</if>
<if test="state != null and state >= 0">
and state like #{state}
</if>
</where>
</select>
4、分页插件支持好几种调用方式:Mapper接口方式的调用,推荐这种使用方式
只有紧跟在PageHelper.startPage
方法后的第一个Mybatis的查询(Select)方法会被分页。
返回 PagerInfo 类型,它里边包含了更丰富的分页信息
Page<User> Page = PageHelper.startPage(1, 10);//第1页的10个数据
//List<User> userList = userMapper.selectUserBylike("admin",1);
List<User> userList = userMapper.selectUserBylike(null,null);
//使用PageInfo对象获取,目的是把List强转成Page对象,从而得到分页结果
PageInfo<User> pageInfo = new PageInfo<>(userList);
System.out.println(pageInfo);
System.out.println(pageInfo.getTotal());
System.out.println(pageInfo.isHasNextPage());
注意:什么时候会导致不安全的分页?
PageHelper
方法使用了静态的 ThreadLocal
参数,分页参数和线程是绑定的。
只要你可以保证在 PageHelper
方法调用后紧跟 MyBatis 查询方法,这就是安全的。因为 PageHelper
在 finally
代码段中自动清除了 ThreadLocal
存储的对象。
如果代码在进入 Executor
前发生异常,就会导致线程不可用,这属于人为的 Bug(例如接口方法和 XML 中的不匹配,导致找不到 MappedStatement
时), 这种情况由于线程不可用,也不会导致 ThreadLocal
参数被错误的使用。