1.无条件分页:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace写成类的全限定名有好处,在Dao中方便-->
<mapper namespace="com.winner.entity.Student">
<!--type是类的全限定名,因为mybatis.xml中有别名的设置,所以用别名,短,方便-->
<resultMap id="studentMap" type="Student">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sal" column="sal"/>
</resultMap>
<!--这里做一个约定,返回值类型以后都写resultMap的id-->
<!--SQL语句这样写易读性更好-->
<select id="findAllWithPage" parameterType="map" resultMap="studentMap"> SELECT id,name,sal FROM student LIMIT #{pstart},#{psize} </select>
</mapper>
public class StudentDao { /** * 无条件分页 * @param start 表示在mysql中从第几条记录的索引号开始显示,索引从0开始 * @param size 表示在mysql中最多显示几条记录 */
public List<Student> findAllWithPage(int start,int size) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); Map<String,Object> map = new LinkedHashMap<String,Object>(); map.put("pstart",start); map.put("psize",size); return sqlSession.selectList(Student.class.getName() + ".findAllWithPage", map); }catch(Exception ex){ ex.printStackTrace(); throw ex; }finally{ MybatisUtil.closeSqlSession(); } } public static void main(String[] args) throws Exception{ StudentDao dao = new StudentDao(); System.out.println("--------------------第一页"); List<Student> studentList1 = dao.findAllWithPage(0,3); for(Student s : studentList1){ System.out.println(s.getId() + " : " + s.getName() + " : " + s.getSal()); } System.out.println("--------------------第二页"); List<Student> studentList2 = dao.findAllWithPage(3,3); for(Student s : studentList2){ System.out.println(s.getId() + " : " + s.getName() + " : " + s.getSal()); } System.out.println("--------------------第三页"); List<Student> studentList3 = dao.findAllWithPage(6,3); for(Student s : studentList3){ System.out.println(s.getId() + " : " + s.getName() + " : " + s.getSal()); } System.out.println("--------------------第四页"); List<Student> studentList4 = dao.findAllWithPage(9,3); for(Student s : studentList4){ System.out.println(s.getId() + " : " + s.getName() + " : " + s.getSal()); } } }
2.带条件的分页
<select id="findAllByNameWithPage" parameterType="map" resultMap="studentMap"> SELECT id,name,sal FROM student WHERE name LIKE #{pname} limit #{pstart},#{psize} </select>
/** * 有条件分页 */
public List<Student> findAllByNameWithPage(String name,int start,int size) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); Map<String,Object> map = new LinkedHashMap<String, Object>(); map.put("pname","%"+name+"%"); map.put("pstart",start); map.put("psize",size); return sqlSession.selectList(Student.class.getName()+".findAllByNameWithPage",map); }catch(Exception ex){ ex.printStackTrace(); throw ex; }finally{ MybatisUtil.closeSqlSession(); } }