MyBatis-分页
八、分页
1、为什么要分页?
- 减少数据的处理量
2、使用limit分页
语法:select * from `表名` limit startIndex,pageSize;
select * from `表名` limit pageSize; #从index=0开始查
3、使用MyBatis实现分页
//实现分页查询
List<User> getUserByLimit(HashMap<String,Integer> map);
<select id="getUserByLimit" parameterType="map" resultMap="userMap">
select * from mybatis.user limit #{startIndex},#{pageSize};
</select>
//分页查询
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex",1);
map.put("pageSize",2);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
4、RowBounds实现分页
不再使用SQL实现分页
//RowBounds实现分页
List<User> getUserByRowBounds();
<select id="getUserByRowBounds" resultMap="userMap">
select * from mybatis.user;
</select>
//RowBounds实现分页查询
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
RowBounds rowBounds = new RowBounds(1,2);
List<User> userList = sqlSession.selectList
("com.lengzher.Dao.UserMapper.getUserByRowBounds", null, rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}