一:PageHelper的maven坐标
<!--分页工具类-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
</dependency>
二:在mybatis配置文件中增加插件配置
<plugins>
<!-- 配置分页助手的插件 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 指定数据库方言 -->
<property name="dialect" value="mysql"/>
<!-- 设置为true时,查询结果中会查询出总条数信息 -->
<property name="rowBoundsWithCount" value="true"/>
</plugin>
</plugins>
三:分页查询
分页查询需要当前页和每页大小两个参数,通过PageHelper.setPage方法将参数设置进去,jsqlparser会在sql执行前拦截sql进行分页拼接,如果指定方言是mysql则是limit xx,xx,所以mybatis在自定义sql语句中的末尾尽量不要增加分号;否则拼接的sql语句会有错误。
下面附上一个分页方法案例:
/** * 分页查询品牌 * @param pageNum:当前页数 * @param pageSize:每页大小 * @return:分页结果集 */ @Override public PageResult findPage(int pageNum, int pageSize,TbBrand tbBrand) { PageHelper.startPage(pageNum,pageSize); TbBrandExample example = new TbBrandExample(); if(tbBrand != null){ TbBrandExample.Criteria criteria = example.createCriteria(); if(StringUtils.isNotEmpty(tbBrand.getName())){ criteria.andNameLike("%"+tbBrand.getName()+"%"); } if(StringUtils.isNotEmpty(tbBrand.getFirstChar())){ criteria.andFirstCharLike("%"+tbBrand.getFirstChar()+"%"); } } Page<TbBrand> page = (Page<TbBrand>) brandMapper.selectByExample(example); return new PageResult(page.getTotal(),page.getResult()); }