三种方法实现分页
分析mysql的分页语句 limlit startIndex,pageSize2
在映射文件SQL语句传入这两个参数即可
1 . 设置一个类,包含这两个参数,parameterType类型为此类,这个方法可行,但是比较麻烦
2 .parameterType设置为Map类型
映射文件
<mapper namespace="cn.sxt.entity.UserMapper">
<select id="selectAll" parameterType="Map" resultType="User">
select * from User limit #{startIndex},#{pageSize}
</select>
</mapper>
Dao的写法
public List<User> getAll(int currentPage,int pageSize ) throws IOException{
SqlSession sqlSession=MyBatisUtil.getSqlSession();
Map<String,Integer> map=new HashMap<String,Integer>();
map.put("startIndex", (currentPage-1)*pageSize);
map.put("pageSize", pageSize);
List<User> list= sqlSession.selectList("cn.sxt.entity.UserMapper.selectAll",map);
sqlSession.close();
return list;
3 .通过RowBounds来实现分页(推荐)
这种方法SQL映射文件不需要做任何改变,dao中需要新建RowBounds对象,RowBounds构造方法两个参数就是index,size
映射文件
<select id="getAll" resultType="User">
select * from User
</select>
dao:
public List<User> getAll(int currentPage,int pageSize ) throws IOException{
SqlSession sqlSession=MyBatisUtil.getSqlSession();
RowBounds rowBounds=new RowBounds( (currentPage-1)*pageSize,pageSize);
List<User> list= sqlSession.selectList("cn.sxt.entity.UserMapper.getAll",null,rowBounds);
sqlSession.close();
return list;
}