1. 程式人生 > 實用技巧 >Mybatis-04-分頁

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