MyBatis分頁插件的使用——PageHelper
來源:程序員人生 發(fā)布時(shí)間:2016-06-23 15:10:36 閱讀次數(shù):7540次
1,配置plugin
在myBatis的配置文件中,加入以下配置:
<configuration>
<!-- 配置分頁插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 指定使用的數(shù)據(jù)庫是甚么 -->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
</configuration>
PS:
該插件目前支持以下數(shù)據(jù)庫的物理分頁:
Oracle
Mysql
MariaDB
SQLite
Hsqldb
PostgreSQL
DB2
SqlServer(2005,2008)
Informix
H2
SqlServer2012
配置dialect
屬性時(shí),可使用小寫情勢:
oracle
,mysql
,mariadb
,sqlite
,hsqldb
,postgresql
,db2
,sqlserver
,informix
,h2
,sqlserver2012
在4.0.0版本以后,dialect
參數(shù)可以不配置,系統(tǒng)能自動(dòng)辨認(rèn)這里提到的所有數(shù)據(jù)庫。
對(duì)不支持的數(shù)據(jù)庫,可以實(shí)現(xiàn)com.github.pagehelper.parser.Parser
接口,然后配置到dialect
參數(shù)中(4.0.2版本增加)。
2,引入jar包或通過其他方式配置依賴
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
3,分頁步驟
1,通過PageHelper.startPage(page,rows)開始分頁;
2,通過PageInfo獲得分頁結(jié)果;
@Test
public void testPageHelper() throws Exception{
//1,取得mapper代理對(duì)象
ApplicationContext application=new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
TbItemMapper itemMapper=application.getBean(TbItemMapper.class);
//2,設(shè)置分頁
PageHelper.startPage(1, 30);
//3,履行查詢
TbItemExample example=new TbItemExample();
List<TbItem>list=itemMapper.selectByExample(example);
//4,獲得分頁結(jié)果
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);
}
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)