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();
}