1.PageHelper简介
逆向工程生成的代码是不支持分页处理的(只支持单表查询,增删改任意),如果想进行分页需要自己编写mapper,这样就失去逆向工程的意义了。为了提高开发效率可以使用mybatis的分页插件PageHelper。
PageHelper是mybatis的一个分页插件,该插件目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库分页。
2.PageHelper的使用
第一步:添加jar包,官方提供的代码对逆向工程支持的不好,此处使用参考资料中的pagehelper-fix(一个maven工程)
第二步:在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>
第三步:测试使用
@Test
public void fun1(){
//初始化spring容器
ApplicationContext app = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
//从容器中获得Mapper代理对象
TbItemMapper itemMapper = app.getBean(TbItemMapper.class);
//执行sql语句之前设置分页信息使用PageHelper的startPage方法(当前页,每页显示条数)
PageHelper.startPage(1, 10);
//执行查询
TbItemExample example = new TbItemExample();
List<TbItem> list = itemMapper.selectByExample(example);
//取分页信息,PageInfo。1、总记录数2、总页数 。当前页码
PageInfo<TbItem> pageInfo = new PageInfo<>(list);
System.out.println(pageInfo.getTotal());
System.out.println(pageInfo.getPages());
System.out.println(list.size());
}