本文章涉及环境版本:
- mysql 5.7
- Mybatis 3.5.x
- Maven 3.6.x
- JDK 1.8
项目代码仓库:
https://github.com/Gang-bb/Study-Record/tree/main/bzhan-mybatis-study
需要clone整个bzhan-mybatis-study项目
(整体是一个maven多module工程)
该文章对应:《bzhan-mybatis-study04 》module项目
思考:为什么要分页?
- 减少数据的处理量
1. limit分页
语法:SELECT * from user limit startIndex,pageSize;
mybatis代码实现:
- UserMapper接口中添加
List<User> getUserListByLimit(Map map);
- UserMapper.xml文件中添加查询语句
<select id="getUserListByLimit" parameterType="map" resultType="User">
SELECT * from user limit #{startIndex},#{pageSize};
</select>
- 测试
@Test
public void testLimit(){
SqlSession sqlSession = null;
try {
//1. 获取sqlsession对象
sqlSession = MybatisUtil.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map map = new HashMap();
map.put("startIndex", 0);
map.put("pageSize", 2);
List<User> userList = userMapper.getUserListByLimit(map);
for (User user: userList){
System.out.println(user);
}
} finally {
//3. 关闭sqlsession
sqlSession.close();
}
}
- 结果
2. RowBounds分页
- UserMapper接口中添加
List<User> getUserRowBounds();
- UserMapper.xml文件中添加查询语句
<select id="getUserRowBounds" resultType="User">
select * from user
</select>
- 测试
@Test
public void testRowBounds(){
SqlSession sqlSession = null;
try {
//1. 获取sqlsession对象
sqlSession = MybatisUtil.openSession();
//RowBounds实现
RowBounds rowBounds = new RowBounds(0, 2);
//通过Java代码层面实现分页
List<User> userList = sqlSession.selectList("getUserRowBounds",null,rowBounds);
for (User user: userList){
System.out.println(user);
}
} finally {
//3. 关闭sqlsession
sqlSession.close();
}
}
- 结果
3. 分页插件–Mybatis-pagehelper
看文档即可。很详细!