mybaytis分页插件原理
配置插件:pegehelper
该插件目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库分页。
使用方法:
第一步:需要在SqlMapConfig.xml,配置plugin。
第二步:在sql语句执行之前,添加一个PageHelper。startPage(page,roes)
第三步:取分页结果,创建一个PageInfo对象需要参数,查询结构返回list。从PageInfo对象中取分页结果。
具体执行
配置插件:
添加jar包,在pom文件中添加
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.4.2-fix</version>
mybatis配置文件中添加
<plugins>
<plugininterceptor="com.github.pagehelper.PageHelper">
<!--制定使用的数据库是什么-->
<propertyname="dialect"value="mysql"/>
</plugin>
</plugins>
测试类测试:
publicclassTestPageHelper{
@Test
publicvoidtestPageHelper()throwsException{
//获取mapper代理对象
ApplicationContextapplicationContext=newClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
TbItemMapperitemMapper=applicationContext.getBean(TbItemMapper.class);
//设置分页
PageHelper.startPage(1,30);
//执行查询
TbItemExampleexample=newTbItemExample();
List<TbItem>list=itemMapper.selectByExample(example);
System.out.println("list="+list);
//取分页后结果
PageInfo<TbItem>pageIfo=newPageInfo<>(list);
longtotal=pageIfo.getTotal();
System.out.println("total="+total);
intpages=pageIfo.getPages();
System.out.println("pages="+pages);
intpageSize=pageIfo.getPageSize();
System.out.println("pageSize="+pageSize);
}
}
执行结果