1、就是直接使用我们的SQL语句进行分页,也就是在Mapper里面加上分页的语句就好了。比如MySQL添加一个limit 2,4。这种方式弊端很大,比如我们不用MySQL了,所有的代码都要修改。
2、MyBatis中的分页的插件PageHelper,
3、自己手写分页框架。这种用的比较少,不是说写不出来,你写出来的性能可能没有开源的好,没有经过严格测试容易莫名出现问题。
综合考虑,使用MyBatis的分页插件PageHelper写最方便好用!
如何用MyBatis的分页插件PageHelper写分页:
1,复制jar包
分页jar包下载地址:PageHelper的jar包 - 万策云盘
2,我用IDEA来做演示,将jar包导入到项目中。
3,配置文件,去Mybatis总配置文件“mybatis-config.xml”中插入以下代码。
以下代码插入到 “实体类别名” 和 “数据库配置中间”,位置不能错!
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 方言 -->
<property name="dialect" value="mysql"/>
<!-- 该参数默认为false -->
<!-- 设置为true时,使用RowBounds分页会进行count查询 -->
<property name="rowBoundsWithCount" value="true"/>
</plugin>
</plugins>
4, 根据自己的数据编写main方法进行测试即可。
//查询结果之前 分页 当前页(正常页码) 每页行数
PageHelper.startPage(1,3);//分页
List<News> list= nm.selectByExampleWithBLOBs(null);
PageInfo<News> info=new PageInfo<>(list);//分页对象 pagebean
System.out.println(info.getTotal());//共多少行
System.out.println(info.getPages());//共多少页
System.out.println(info.getPrePage());//上一页
System.out.println(info.getNextPage());//下一页
System.out.println(info.getPageNum());//当前页
for (News n:info.getList() //每页的数据
) {
System.out.println(n.getNid()+"");
}
博主来自:廖万里的博客