当前位置: 移动技术网 > IT编程>数据库>其他数据库 > Mybatis分页插件的实例详解

Mybatis分页插件的实例详解

2017年12月01日  | 移动技术网IT编程  | 我要评论
mybatis分页插件的实例详解 1.前言: 我们知道,在mysql中,分页的sql是使用limit来做,如果我们自己写sql,那分页肯定是没有任何问题的。但是一旦

mybatis分页插件的实例详解

1.前言:

我们知道,在mysql中,分页的sql是使用limit来做,如果我们自己写sql,那分页肯定是没有任何问题的。但是一旦model多了起来,复杂了起来,我们很自然的想到使用mybatis的逆向工程来生成相应的po和mapper,但是同时也会带来弊端,比如这里的分页问题就不好解决了。

  可能有人会说,我可以修改生成的文件,没错,这是可行的,但是一般我们通过逆向工程生成的文件,都不会去动它,所以这个时候,就需要使用分页插件来解决了。

如果你也在用mybatis,建议尝试该分页插件,这个一定是最方便使用的分页插件。

该插件目前支持oracle,mysql,mariadb,sqlite,hsqldb,postgresql六种数据库分页。

 2.使用方法

第一步:在mybatis配置xml中配置拦截器插件:

<plugins>
 <!-- com.github.pagehelper为pagehelper类所在包名 -->
 <plugin interceptor="com.github.pagehelper.pagehelper">
  <!-- 设置数据库类型 oracle,mysql,mariadb,sqlite,hsqldb,postgresql六种数据库-->  
  <property name="dialect" value="mysql"/>
 </plugin>
</plugins>

第二步:在代码中使用

1、设置分页信息:

//获取第1页,10条内容,默认查询总数count
pagehelper.startpage(1, 10);
 //紧跟着的第一个select方法会被分页
list<country> list = countrymapper.selectif(1);

2、取分页信息

//分页后,实际返回的结果list类型是page<e>,如果想取出分页信息,需要强制转换为page<e>,
page<country> listcountry = (page<country>)list;
listcountry.gettotal();

3、取分页信息的第二种方法

//获取第1页,10条内容,默认查询总数count
pagehelper.startpage(1, 10);
list<country> list = countrymapper.selectall();
//用pageinfo对结果进行包装
pageinfo page = new pageinfo(list);
//测试pageinfo全部属性
//pageinfo包含了非常全面的分页属性
assertequals(1, page.getpagenum());
assertequals(10, page.getpagesize());
assertequals(1, page.getstartrow());
assertequals(10, page.getendrow());
assertequals(183, page.gettotal());
assertequals(19, page.getpages());
assertequals(1, page.getfirstpage());
assertequals(8, page.getlastpage());
assertequals(true, page.isfirstpage());
assertequals(false, page.islastpage());
assertequals(false, page.ishaspreviouspage());
assertequals(true, page.ishasnextpage());

 3.testpagehelper

@test
public void testpagehelper() {
 //创建一个spring容器
 applicationcontext applicationcontext = new classpathxmlapplicationcontext("classpath:spring/applicationcontext-*.xml");
 //从spring容器中获得mapper的代理对象
 tbitemmapper mapper = applicationcontext.getbean(tbitemmapper.class);
 //执行查询,并分页
 tbitemexample example = new tbitemexample();
 //分页处理
 pagehelper.startpage(2, 10);
 list<tbitem> list = mapper.selectbyexample(example);
 //取商品列表
 for (tbitem tbitem : list) {
  system.out.println(tbitem.gettitle());
 }
 //取分页信息
 pageinfo<tbitem> pageinfo = new pageinfo<>(list);
 long total = pageinfo.gettotal();
 system.out.println("共有商品:"+ total);
}



感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网