Fork me on GitHub

Mybatis-04-分页

分页

思考:为什么要分页?

  • 减少数据的处理量

1 使用limit分页

select * from user limit startIndex,pageSize;

使用Mybatis实现分页,核心是SQL

  1. 接口
List<User> getUserByLimit(HashMap<String,Integer> map);
  1. Mapper.XML
<!--分页-->
<select id="getUserByLimit" parameterType="map" resultType="User">
    select * from mybatis.user limit #{startIndex},#{pageSize};
</select>
  1. 测试

    @Test
    public void getUserByLimit(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
        HashMap<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();
    }
    

keymap: list.for 可以快速生成增强for循环

2 RowBounds分页

不再使用SQL实现分页

  1. 接口

    List<User> getUserByRowBounds();
    
  1. mapper.xml

    <!--分页-->
    <select id="getUserByRowBounds" resultType="User">
        select * from mybatis.user ;
    </select>
    
  2. 测试

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

3 分页插件

Mybatis pageHelper

posted @ 2020-08-09 16:40  CodeHuba  阅读(69)  评论(0编辑  收藏  举报