一. Mybatis分頁插件PageHelper使用
1、不使用插件如何分頁:
使用mybatis實現:
1)接口:
List<Student> selectStudent(Map<String, Object> map);
2)mapper.xml:
<select id="selectStudent" resultMap="BaseResultMap" parameterType="java.util.Map" > select <include refid="Base_Column_List" /> from student limit #{pageNum},#{pageSize} </select>
3)測試:
@Test public void TestGetStudent() throws IOException { try { StudentMapper mapper=session.getMapper(StudentMapper.class); Map<String,Object> map=new HashMap<String,Object>(); map.put("pageNum", 0); map.put("pageSize", 3); List<Student> students=mapper.selectStudent(map); for(Student student :students) System.out.println(student.gettId() + " " + student.gettName() + " "+student.gettAge()+" "+student.gettEnterdate()+" "+student.gettSid()); }finally { session.close(); } }
2 使用PageHelper插件如何分頁:
下載地址:
https://github.com/pagehelper/Mybatis-PageHelper
https://github.com/JSQLParser/JSqlParser
另外一個地址:
Pagehelper下載地址:
http://repo1.maven.org/maven2/com/github/pagehelper/pagehelper/
jsqlparser 下載地址:
http://repo1.maven.org/maven2/com/github/jsqlparser/jsqlparser/
使用步驟:
1、導入相關包pagehelper-x.x.x.jar 和 jsqlparser-x.x.x.jar。
2、在MyBatis全局配置文件中配置分頁插件。
<plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin> </plugins>
3、使用PageHelper提供的方法進行分頁
StudentMapper mapper = session.getMapper(StudentMapper.class); //放在查詢之前 Page<Object> page = PageHelper.startPage(1, 3); StudentExample example=null; List<Student> students=mapper.selectByExample(example); for(Student student :students) System.out.println(student.gettId() + " " + student.gettName() + " "+student.gettAge()+" "+student.gettEnterdate()+" "+student.gettSid()); System.out.println("當前頁碼:"+page.getPageNum()); System.out.println("總記錄數:"+page.getTotal()); System.out.println("每頁的記錄數:"+page.getPageSize()); System.out.println("總頁碼:"+page.getPages());
4、可以使用更強大的PageInfo封裝返回結果
StudentMapper mapper = session.getMapper(StudentMapper.class); Page<Object> page = PageHelper.startPage(1, 3); StudentExample example=null; List<Student> students=mapper.selectByExample(example); for(Student student :students) System.out.println(student.gettId() + " " + student.gettName() + " "+student.gettAge()+" "+student.gettEnterdate()+" "+student.gettSid()); PageInfo<Student> info = new PageInfo<Student>(students, 3); System.out.println("當前頁碼:"+info.getPageNum()); System.out.println("總記錄數:"+info.getTotal()); System.out.println("每頁的記錄數:"+info.getPageSize()); System.out.println("總頁碼:"+info.getPages()); System.out.println("是否第一頁:"+info.isIsFirstPage()); System.out.println("連續顯示的頁碼:"); int[] nums = info.getNavigatepageNums(); for (int i = 0; i < nums.length; i++) { System.out.println(nums[i]); }