SSM框架学习之路-Mybatis(七)分页

7、分页

**思考:**为什么要使用分页?

  • 减少数据处理量

使用Limit分页

-- 语法: select * from mybatis.user limit startIndex, pageSize;
select * from mybatis.user limit 3; -- [0, n]

使用Mybatis分页,核心SQL

  1. 接口

    // 分页获取用户
    public List<User> getUserByLimit(Map<String, Integer> map);
    
  2. Mapper.xml

    
    <select id="getU serByLimit" parameterType="map" resultMap="userMap">
        select * from mybatis.user limit #{startIndex}, #{pageSize}
    select>
    
  3. 测试

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

7.2、RowBounds分页

不再使用SQL实现分页

  1. 接口

    // 分页2
    public List<User> getUserByRowBounds();
    
  2. Mapper.xml

    
    <select id="getUserByRowBounds" resultMap="userMap">
        select * from mybatis.user
    select>
    
  3. 测试

    @Test
    public void getUserByRowBounds() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        // RowBounds实现
        RowBounds rowBounds = new RowBounds(1, 2);
        // 通过java代码层实现分页
        List<User> users = sqlSession.selectList("com.wsw.dao.UserMapper.getUserByRowBounds", null, rowBounds);
        for (User user : users) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    

7.3、分页插件

SSM框架学习之路-Mybatis(七)分页_第1张图片

了解即可,需要知道它是什么东西。

你可能感兴趣的:(mybatis基础学习)