您的位置:首页 > 其它

MyBatis分页插件的使用——PageHelper

2016-05-29 21:05 447 查看

一,配置plugin

在myBatis的配置文件中,加入如下配置:

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

</configuration>


PS:

该插件目前支持以下数据库的物理分页:

Oracle

Mysql

MariaDB

SQLite

Hsqldb

PostgreSQL

DB2

SqlServer(2005,2008)

Informix

H2

SqlServer2012

配置
dialect
属性时,可以使用小写形式:

oracle
,
mysql
,
mariadb
,
sqlite
,
hsqldb
,
postgresql
,
db2
,
sqlserver
,
informix
,
h2
,
sqlserver2012


在4.0.0版本以后,
dialect
参数可以不配置,系统能自动识别这里提到的所有数据库。

对于不支持的数据库,可以实现
com.github.pagehelper.parser.Parser
接口,然后配置到
dialect
参数中(4.0.2版本增加)。

二,引入jar包或通过其他方式配置依赖

<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>


三,分页步骤

1,通过PageHelper.startPage(page,rows)开始分页;

2,通过PageInfo获取分页结果;

@Test
public void testPageHelper() throws Exception{
//1,获得mapper代理对象
ApplicationContext application=new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
TbItemMapper itemMapper=application.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<TbItem>(list);
long total=pageInfo.getTotal();
System.out.println(total);
int pages=pageInfo.getPages();
System.out.println(pages);
int pageSize=pageInfo.getPageSize();
System.out.println(pageSize);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: