MyBatis中使用RowBounds對查詢結果集進行分頁


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的分頁輔助工具來完成分頁


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM