Mybatis使用limit实现分页,前面的创建Maven项目,导入所需依赖包等环境在这里不再介绍。
主要实现过程如下:
一、编写Mapper接口。
List<Stu> getStuByLimit(Map<String,Integer> map); //分页
二、编写Mapper对应的映射文件。
<!--分页-->
<select id="getStuByLimit" resultMap="StuMap" parameterType="map" >
select * from stu limit #{startIndex},#{pageSize}
</select>
注:
详见上篇:Mybatis框架(八)ResultMap结果集映射的简单使用
三、编写测试方法。
@Test
public void getStuByLimit(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StuMapper mapper = sqlSession.getMapper(StuMapper.class);
HashMap<String, Integer> map = new HashMap();
int startIndex=0; //起始位置
int pageSize=3; //页面大小
map.put("startIndex",startIndex);
map.put("pageSize",pageSize);
List<Stu> stuList = mapper.getStuByLimit(map);
for (Stu stu : stuList) {
System.out.println(stu);
}
sqlSession.close();
}