思考:为什么分页?
减少数据的处理量
7.1、使用Limit分页
语法: **select **_* _**from user limit **startIndex,pageSize
使用Mybatis实现分页,核心SQL
1.接口
//分页limit
List<User> getUserLimit(Map<String, Integer> map);
2.配置文件
<!--分页limit-->
<select id="getUserLimit" parameterType="map" resultMap="UserMap">
select *
from mybatis.user limit #{startIndex},#{pageSize}
</select>
3.测试
//分页limit
@Test
public void getUserLimit() {
//第一步: 获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
//执行SQL方式一: getMapper(推荐)
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex", 0);
map.put("pageSize", 4);
List<User> userList = userMapper.getUserLimit(map);
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭SqlSession
sqlSession.close();
}
}
7.2、RowBounds类
不再使用SQL实现分页
1.接口
//分页RowBounds
List<User> getUserRowBounds(Map<String, Integer> map);
2.配置文件
<!--分页RowBounds-->
<select id="getUserRowBounds" parameterType="map" resultMap="UserMap">
select *
from mybatis.user
</select>
3.测试
//分页RowBounds
@Test
public void getUserRowBounds(){
//第一步: 获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
//执行SQL: getMapper(推荐)
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//RowBounds实现
RowBounds rowBounds = new RowBounds(0, 2);
//通过java代码的层面去实现分页
List<User> userList = sqlSession.selectList("com.dao.UserMapper.getUserRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭SqlSession
sqlSession.close();
}
}
7.3、分页插件
了解即可,
![image.png](https://img-blog.csdnimg.cn/img_convert/367b87be8b600bd951fdc45df11a1e0f.png#clientId=ude78a7ef-2a21-4&from=paste&height=275&id=ue1bbb0ff&margin=[object Object]&name=image.png&originHeight=549&originWidth=1641&originalType=binary&ratio=1&size=72862&status=done&style=none&taskId=u4e4858d2-1786-44f9-9d95-c1c3194dc2d&width=820.5)
使用方法: https://pagehelper.github.io/docs/howtouse/#1-%E5%BC%95%E5%85%A5%E5%88%86%E9%A1%B5%E6%8F%92%E4%BB%B6