返回顶部
2 3 4

MyBatis(七)分页

7、分页

7.1 使用limit分页

#语法
SELECT * FROM table LIMIT stratIndex,pageSize

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

#为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1:   
SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.  

#如果只给定一个参数,它表示返回最大的记录行数目:   
SELECT * FROM table LIMIT 5; //检索前 5 个记录行  

#换句话说,LIMIT n 等价于 LIMIT 0,n。 

使用Mybatis实现分页,核心SQL

  1. 接口
//分页
List<User> getUserByLimit(Map<String,Integer> map);
  1. Mapper.xml
<select id="selectUser" parameterType="map" resultType="user">
  select * from user limit #{startIndex},#{pageSize}
</select>
  1. 在测试类中传入参数测试

    推断:起始位置 = (当前页面 - 1 ) * 页面大小

@Test
public void getUserLimit() throws IOException {
    SqlSession sqlSession=MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("startIndex",1);
    map.put("pageSize",2);
    List<User> userList = mapper.getUserByLimit(map);
    for (User user : userList) {
        System.out.println(user);
    }
}

7.2、RowBounds分页

不再使用SQL实现分页,体现java面向对象思想,不常用,看得懂就好

  1. 接口
//分页2
List<User> getUserByRowBounds(Map<String,Integer> map);
  1. Mapper.xml
<!--分页2-->
<select id="getUserByRowBounds"  resultMap="UserMap">
    select * from mybatis.user
</select>
  1. 测试
@Test
public void getUserRowBounds() throws IOException {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    //RowBounds实现
    int currentPage = 2;  //第几页
    int pageSize = 2;  //每页显示几个
    RowBounds rowBounds = new RowBounds(currentPage, pageSize);

    //通过Java代码实现分页
    List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRowBounds",null,rowBounds);
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}
posted @ 2021-08-16 19:12  硫没有正七价  阅读(34)  评论(0编辑  收藏  举报