您的位置:首页 > 其它

Mybatis之分页插件——PageHelper

2017-08-18 15:54 495 查看

Mybatis之分页插件——PageHelper

为什么使用PageHelper

插件叫做PageHelper如果你也在用Mybatis,建议尝试该分页插件。个人认为非常好用

该插件目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库分页。

使用方法:

第一步:导入jar包

第二步:需要在SqlMapConfig.xml,配置一个plugin。

第三步:在sql语句执行之前,添加一个PageHelper.startPage(page,rows);

第四步:取分页结果。创建一个PageInfo对象需要参数,查询结果返回的list。从PageInfo对象中取分页结果。

具体演示

导入jar包

-mybatis-paginator-1.2.15.jar

-pagehelper-3.4.2-fix.jar

这两个jar包在网上找找即可。

修改SqlMapConfig.xml

<configuration></configuration>
标签里面,添加如下配置

<!-- 配置分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 指定使用的数据库是什么 -->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>


3.测试代码

//1、加载配置文件,获得mapper代理对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
//获取Mapper
TbItemMapper itemMapper = applicationContext.getBean(TbItemMapper.class);
//2、设置分页
PageHelper.startPage(1, 30);
//3、执行查询
TbItemExample example = new TbItemExample();
List<TbItem> list = itemMapper.selectByExample(example);
//4、取分页后结果
PageInfo<TbItem> pageInfo = new PageInfo<>(list);
long total = pageInfo.getTotal();
System.out.println("total:" + total);
int pages = pageInfo.getPages();
System.out.println("pages:" + pages);
int pageSize = pageInfo.getPageSize();
System.out.println("pageSize:" + pageSize);


以上,希望对大家有所帮助!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  插件 mybatis