MyBatis分頁插件的使用——PageHelper
來源:程序員人生 發布時間:2016-06-23 15:10:36 閱讀次數:7549次
1,配置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版本增加)。
2,引入jar包或通過其他方式配置依賴
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
3,分頁步驟
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);
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈