mybatis学习——实现分页
首先回顾一下分页的sql语句:
SELEC * FROM 表名 LIMIT startIndex,pageSize
tips:
*startIndex:起始的位置(从哪个元素开始分页)
*pageSize:每页多少个元素
例如:
select * from user limit 0,2 :查询user表所有的元素,起始位置是第零个元素,每页2个元素
select * from user limit 3 :查询user表所有的元素,起始位置是第零个元素,每页3个元素
使用mabatis实现分页:
一、使用Limit分页
(1)定义接口
package com.kuang.dao; import com.kuang.pojo.User; import java.util.List; import java.util.Map; public interface UserMapper { List<User> getUserByLimit(Map<String ,Object> map); }
(2)编写映射文件
<?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"> <mapper namespace="com.kuang.dao.UserMapper"> <select id="getUserByLimit" resultMap="user" parameterType="map"> SELECT * FROM mybatis.user LIMIT #{startIndex},#{pageSize} </select> </mapper>
(3)编写测试方法
@Test public void getUserByLimit(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("startIndex",0); map.put("pageSize",2); List<User> userList = mapper.getUserByLimit(map); for (User user : userList) { System.out.println(user); } sqlSession.close(); }