Mybatis-分页
分页
为什么要分页:
- 减少数据的处理量
1. 使用limit分页
select * from user limit 0, 2;
select * from user limit 2, 2;
limit n,m ==> n为页起始的位置(从0开始), m为每页的个数
2. 使用Mybatis实现分页
核心 SQL
1. 使用limit实现
接口
//分页
List<User> getUserByLimit(Map<String, Integer> map);
UserMapper.xml
<!--分页-->
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startIndex}, #{pageSize};
</select>
测试
@Test
public void testGetUserByLimit() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Integer> map = new HashMap<>();
map.put("startIndex", 0);
map.put("pageSize", 2);
List<User> userByLimit = mapper.getUserByLimit(map);
for (User user : userByLimit) {
System.out.println(user);
}
sqlSession.close();
}
2. 使用RowBounds实现分页(了解)
不再使用SQL实现分页
接口
//分页(RowBounds)
List<User> getUserByRowBounds(Map<String, Integer> map);
UserMapper.xml
<!--RowBounds分页-->
<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>
测试
@Test
public void testGetUserByRowBounds() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
//RowBounds实现
RowBounds rowBounds = new RowBounds(0, 2);
//通过Java代码层面实现分页
List<User> userList = sqlSession.selectList("com.wang.dao.UserMapper.getUserByRowBounds", null, rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}