Mybatis分页查询limit

x33g5p2x  于2022-02-07 转载在 其他  
字(1.1k)|赞(0)|评价(0)|浏览(422)

首先,写一下分页查询的原理:sql语句:

  1. #语法
  2. SELECT * FROM table LIMIT stratIndexpageSize
  3. SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15
  4. #为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1:
  5. SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.
  6. #如果只给定一个参数,它表示返回最大的记录行数目:
  7. SELECT * FROM table LIMIT 5; //检索前 5 个记录行
  8. #换句话说,LIMIT n 等价于 LIMIT 0,n。

然后步骤:

1:修改Mapper文件

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

2: Mapper接口,参数为map

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

3: 在测试类中传入参数测试

  1. //分页查询 , 两个参数startIndex , pageSize
  2. @Test
  3. public void testSelectUser() {
  4. SqlSession session = MybatisUtils.getSession();
  5. UserMapper mapper = session.getMapper(UserMapper.class);
  6. int currentPage = 1; //第几页
  7. int pageSize = 2; //每页显示几个
  8. Map<String,Integer> map = new HashMap<String,Integer>();
  9. map.put("startIndex",(currentPage-1)*pageSize);
  10. map.put("pageSize",pageSize);
  11. List<User> users = mapper.selectUser(map);
  12. for (User user: users){
  13. System.out.println(user);
  14. }
  15. session.close();
  16. }

实现分页:

分割线——————————————————————————

分页插件(自行了解:Mybatis——PageHelper)

相关文章