做過一個小項目是關於SpringBoot+SpringMvc+mybatis+pagehelper,這里簡單實現了PageHelper。
先上效果圖:
(實現了功能我就懶到美化都不想美化了,可這並不是問題)
話不多說,直接上手吧。
1、Pom依賴
1 <dependency> 2 <groupId>com.github.pagehelper</groupId> 3 <artifactId>pagehelper</artifactId> 4 <version>5.1.2</version> 5 </dependency>
2、設置Mybatis配置xml中配置攔截器插件,一般在Resource路徑下。我這里叫mybatis-config.xml。
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <typeAliases> 7 <package name="com.ms.pojo"/> 8 </typeAliases> 9 <plugins> 10 <!--com.github.pagehelper為PageHelper類所在包名--> 11 <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin> 12 </plugins> 13 </configuration>
3、配置完mybatis之后,,就以分頁查詢用戶列表為例,添加查詢所有用戶的mapper接口
public List<Student> SelectAllStu();
4、對應的sql語句
1 <select id="SelectAllStu" resultType="student"> 2 select * from info 3 </select>
5、在Controller里面寫業務代碼
1 //查詢所有學生信息 2 @RequestMapping("SelectAllStu") 3 public ModelAndView SelectAllStu(@RequestParam(defaultValue="1") Integer page, 4 HttpServletRequest request,HttpServletResponse response){ 5 PageHelper.startPage(page,5);//每頁5個數據 6 List<Student> list=studentService.SelectAllStu(); 7 PageInfo pageinfo = new PageInfo(list,5); 8 9 ModelAndView model = new ModelAndView(); 10 model.addObject("pageinfo", pageinfo); 11 model.setViewName("showAllStu"); 12 return model; 13 14 }
PageHelper.startPage(pageNum, pageSize);
這句非常重要,這段代碼表示分頁的開始,意思是從第pageNum
頁開始,每頁顯示pageSize
條記錄。
PageInfo
這個類是插件里的類,這個類里面的屬性會在輸出結果中顯示,
使用
PageInfo
這個類,你需要將查詢出來的
list
放進去
6、補充一下,PageHelper的配置我放在了Myconfig里面
1 package com.ms.config; 2 3 import java.util.Properties; 4 5 import org.springframework.context.annotation.Bean; 6 import org.springframework.context.annotation.Configuration; 7 8 import com.github.pagehelper.PageHelper; 9 10 @Configuration 11 public class MyConfig { 12 @Bean 13 public PageHelper pageHelper(){ 14 PageHelper pageHelper = new PageHelper(); 15 Properties properties = new Properties(); 16 /**默認false,設置為true時,會將RowBounds第一個參數offset當成pageNum頁碼使用*/ 17 properties.setProperty("offsetAsPageNum","true"); 18 /**默認false,設置為true時,使用RowBounds分頁會進行count查詢 */ 19 properties.setProperty("rowBoundsWithCount","true"); 20 /** 禁用合理化時,如果pageNum<1或pageNum>pages會返回空數據 */ 21 properties.setProperty("reasonable","true"); 22 /** always總是返回PageInfo類型,check檢查返回類型是否為PageInfo,none返回Page */ 23 properties.setProperty("returnPageInfo","check"); 24 /** 支持通過Mapper接口參數來傳遞分頁參數 */ 25 properties.setProperty("supportMethodsArguments","false"); 26 /** 配置數據庫的方言 */ 27 properties.setProperty("dialect","mysql"); 28 pageHelper.setProperties(properties); 29 return pageHelper; 30 } 31 }
個人感覺,pagehelper還是很不錯的,當然還有其他分頁的方法也可以勇於嘗試哈。