day2
项目名04mybatics_page(复制于项目02)
五、分页的实现
- 分析mysql的分页语句 :
limit startIndex,pageNum
分析mapper映射文件:(查询所有用户)
此处要传的参数parameterType类型应该为Map,需要传入的值分别为起始页StartIndex与每页的限制大小pageSize。
Dao中的写法:
此处采用Map,分别像XML中的startIndex与pageSize传入值。
//分页查询
public List<User> getAll(int currentPage,int pageSize) throws IOException{
SqlSession session = MyBatisUtil.getSession();
Map<String, Integer> map = new HashMap<String,Integer>();
map.put("startIndex", (currentPage-1)*pageSize);
map.put("pageSize", pageSize);
List<User> list = session.selectList("com.mybatis.entity.UserMapper.selectAll",map);
session.close();
return list;
}
注意:不用为参数设置类,可以直接采用Map结构来解决。(即传多个参数)
-
(解决方案2)通过RowBounds实现分页
mapper文件不用做任何改变 (和最初的一样)注意id是getAll
Dao中需要新建RowBounds对象注:RowBounds对象的两个参数
RowBouns rowBounds = new RowBounds(index,size) // index是下标,size是数据
对应的Dao中的参数
//分页查询的第二种方法 RowBounds
public List<User> getAll(int currentPage,int pageSize) throws IOException{
SqlSession session = MyBatisUtil.getSession();
RowBounds rowBounds = new RowBounds((currentPage-1)*pageSize, pageSize);
List<User> list = session.selectList("com.mybatis.entity.UserMapper.getAll",null,rowBounds);
session.close();
return list;
}