Mybatis分页插件的示例分析

31次阅读
没有评论

共计 2281 个字符,预计需要花费 6 分钟才能阅读完成。

自动写代码机器人,免费开通

这篇文章主要介绍 Mybatis 分页插件的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

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);
}

以上是“Mybatis 分页插件的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注丸趣 TV 行业资讯频道!

向 AI 问一下细节

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-04发表,共计2281字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)