好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Mybatis分页插件的实例详解

Mybatis分页插件的实例详解

1.前言:

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

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

如果你也在用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);

}

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

原文链接:http://HdhCmsTestcnblogs测试数据/ganchuanpu/p/6147911.html

查看更多关于Mybatis分页插件的实例详解的详细内容...

  阅读:16次