1.分页原理
分页查询的原理在于两个参数,一个是页码pageno,一个是页尺寸pagesize。
只要这两个参数确定,下面这个伪sql语句就可以查询第pageno页的数据。
select * from student limit (pageno-1)*pagesize,pagesize
2.实现分析
若直接以pageno和pagesize作为参数传递,则mysql无法识别表达式(pageno-1)*pagesize。
所以通常把它综合为一个参数startRow,让表达式(pageno-1)*pagesize在传参前先计算好,赋值给参数startRow。
最终使用的sql语句
select * from student limit startRow,pagesize
3.关键代码
分页要使用到两个参数,所以这里采用了map类型传递多个参数的办法
Map map=new HashMap();
int startRow=(pageno-1)*pagesize;
map.put("startRow",startRow);
map.put("pagesize",pagesize);
在dao层的接口和实现类添加findStudentsByPage(Map map)方法,在映射文件StudentMapepr.xml添加以下代码
<mapper namespace="com.lifeng.dao.IStudentDao">
<!-- 配置结果映射 -->
<resultMap id="studentResultMap" type="Student">
<id property="id" column="id"/>
<result property="sname" column="studentname"/>
<result property="sex" columu="gender"/>
<result property="age" column="age"/>
</resultMap>
<!-- 使用分页查询 -->
<select id="findStudentsByPage" resultMap="studentResultMap" parameterType="java.util.Map">
select * from student limit #{startRow},#{pagesize}
</select>
</mapper>