使用Limit实现分页

limit语法

#语法
SELECT * FROM table LIMIT stratIndex,pageSize

SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15   

#如果只给定一个参数,它表示返回最大的记录行数目:    
SELECT * FROM table LIMIT 5; //检索前 5 个记录行   
 
#换句话说,LIMIT n 等价于 LIMIT 0,n。  

1、 创建接口,参数为map

//选择全部用户实现分页
List<User> selectUser(Map<String,Integer> map);

2、 修改Mapper.xml文件 ,绑定接口

<select id="selectUser" parameterType="map" resultType="user">
    select * from user limit #{startIndex},#{pageSize}
</select>

3、编写测试类

//分页查询 , 两个参数startIndex , pageSize
@Test
public void testSelectUser() {
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);

    int currentPage = 1;  //第几页
    int pageSize = 2;  //每页显示几个
    Map<String,Integer> map = new HashMap<String,Integer>();
    //推断:起始位置 = (当前页面 - 1 ) * 页面大小
    map.put("startIndex",(currentPage-1)*pageSize);
    map.put("pageSize",pageSize);

    List<User> users = mapper.selectUser(map);

    for (User user: users){
        System.out.println(user);
    }

    session.close();
}
原文地址:https://www.cnblogs.com/gkblog/p/12298111.html