您的位置:首页 > 其它

MyBatis知识系列之五:利用Mybatis实现数据表的分页

2016-04-20 15:29 489 查看
1、分析mysql的分页语句:limitstartIndex,pageNum

mapper映射文件

<!-- 查询所有用户 -->
<select
id="selectAll"
parameterType="Map"
resultType="User">
select * from user limit #{startIndex},#{pageSize}
</select>

Dao中的写法

//分页查询
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("cn.sxt.entity.UserMapper.selectAll",map);
session.close();
return list;
}

注意:不用为参数设置类,可以采用map结构来解决这个问题。

2、通过RowBounds来实现分页

Mapper文件不用做任何改变

<select
id="getAll"
resultType="User">
select * from user
</select>

Dao中需要新建RowBounds对象

RowBoundsrowBounds=new RowBounds(index,size);index是下标,size数据

//分页查询
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("cn.sxt.entity.UserMapper.getAll",null,rowBounds);
session.close();
return list;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: