1.说明
如果你也在用Mybatis,建议尝试该分页插件,这个一定是最方便使用的分页插件。
该插件目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库分页。
2.使用方法
第一步:在Mybatis配置xml中配置拦截器插件:
1
2
3
4
5
6
7
|
<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
2
3
4
|
//获取第1页,10条内容,默认查询总数count PageHelper.startPage( 1 , 10 ); //紧跟着的第一个select方法会被分页 List<Country>
list = countryMapper.selectIf( 1 ); |
2、取分页信息
1
2
3
|
//分页后,实际返回的结果list类型是Page<E>,如果想取出分页信息,需要强制转换为Page<E>, Page<Country>
listCountry = (Page<Country>)list; listCountry.getTotal(); |
3、取分页信息的第二种方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
//获取第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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
@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); } |