1. 使用limit分页
select * from mybatis.user limit #{startIndex},#{pageSize};
#{startIndex}:起始查询的下标;
#{pageSize}:一页查询的条数
例子
接口
List<User> getUserByLimit(Map<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);//拿到操作对象mapper
HashMap<String,Integer> map=new HashMap<String, Integer>();
map.put("startIndex",0);//存参数
map.put("pageSize",2);
List<User> userList=mapper.getUserByLimit(map);//传参,返回结果集
for (User user : userList) {
System.out.println(user);//输出
}
sqlSession.close();
}
2. RowBounds分页
通过java代码实现分页
// RowBound实现
RowBounds rowBounds=new RowBounds(1,2);//RowBounds(起始下标,条数);
//通过java代码层面实现分页
List<User> userList=sqlSession.selectList("com.ming.dao.UserMapper.getUserByRowBounds",null,rowBounds);
例子
接口
List<User> getUserByRowBounds();
接口实现
<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>
测试
@Test
public void getUserByRowBounds(){
SqlSession sqlSession=MybatisUtils.getSqlSession();
// RowBound实现
RowBounds rowBounds=new RowBounds(1,2);
//通过java代码层面实现分页
List<User> userList=sqlSession.selectList("com.ming.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}