020.PageHelper分页插件
1.分页查询要面临的问题
2.使用流程
2.1 pom.xml
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.10</version> </dependency> <dependency> <groupId>com.github.jsqlparser</groupId> <artifactId>jsqlparser</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.4</version> </dependency>
2.2 mybatis-config.xml
<!--启用Pagehelper分页插件--> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!--设置数据库类型--> <property name="helperDialect" value="mysql"/> <!--分页合理化--> <property name="reasonable" value="true"/> </plugin> </plugins>
2.3 分页的处理
2.3.1 goods.xml
<select id="selectPage" resultType="com.imooc.mybatis.entity.Goods">
select * from t_goods where current_price < 1000
</select>
2.3.2 测试类
@Test /** * PageHelper分页查询 */ public void testSelectPage() throws Exception { SqlSession session = null; try { session = MyBatisUtils.openSession(); /*startPage方法会自动将下一次查询进行分页*/ PageHelper.startPage(2,10); Page<Goods> page = (Page) session.selectList("goods.selectPage"); System.out.println("总页数:" + page.getPages()); System.out.println("总记录数:" + page.getTotal()); System.out.println("开始行号:" + page.getStartRow()); System.out.println("结束行号:" + page.getEndRow()); System.out.println("当前页码:" + page.getPageNum()); List<Goods> data = page.getResult();//当前页数据 for (Goods g : data) { System.out.println(g.getTitle()); } System.out.println(""); } catch (Exception e) { throw e; } finally { MyBatisUtils.closeSession(session); } }