MyBatis可以使用RowBounds逐頁加載表數據。RowBounds對象可以使用offset和limit參數來構建。參數offset表示開始位置,而limit表示要取的記錄的數目
映射文件:
<select id="findAllUsers" resultType="User"> select id,name,gender from t_user </select>
映射接口中:
public List<User> findAllUsers(RowBounds rowBounds);
測試方法:
@Test public void test_findAllUsers2(){ SqlSession sqlSession = null; try { sqlSession = MyBatisSqlSessionFactory.openSession(); SpecialMapper mapper = sqlSession.getMapper(SpecialMapper.class); //表示從第幾條數據開始 int offset = 0; //連續取出幾條數據 int limit = 5; RowBounds rowBounds = new RowBounds(offset, limit); List<User> list = mapper.findAllUsers(rowBounds); list.forEach(System.out::println); } catch (Exception e) { e.printStackTrace(); } }
注意,若規定每頁5條數據,要展示第二頁,使用offset=5,limit=5
但是其實Mybatis的分頁是基於內存的分頁(查出所有記錄再按偏移量和limit取結果),在大數據量的情況下這樣的分頁效率會很低,一般情況下我們會使用mybaits的分頁輔助工具來完成分頁