一. 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]);
}