1. 程式人生 > 其它 >【Mybatis 框架(自學)】Day05--2022/3/13

【Mybatis 框架(自學)】Day05--2022/3/13

分頁

為什麼要分頁

  • 為了減少資料的處理量,所以採用分頁功能

使用Limit分頁

SELECT * FROM 表明 limit startIndex,pageSize;
//介面實現類定義分頁查詢方法
public interface StudentMapper{
    
    List<Student> selectStudentByLimit(Map<String,Object> map);
    
}
<!--Mapper對映-->
<select id="selectStudentByLimit" parameterType="map" resultType="Student">
	select * from tbstudent limit #{startIndex},#{pageSize}
</select>
//Junit測試
@Test
public void selectStudentByLimit(){
    SqlSession sqlSession = MybatisUtils.getConnection();
    StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
    
    try{
        Map<String,Object> map = new HashMap<>();
        map.put("startIndex",0);
        map.put("pageSize",3)
        List<Student> studentList = studentMapper.selectStudentByLimit(map);
        for(Student student:studentList){
            sout(student);
        }
    }catch(Exception e){
        e.prinStackTrace();
    }finally{
        closeSqlSession(sqlSession)
    }
}

RowBounds分頁

select * from 表明 (因為此查詢操作直接面向物件來生成,不再使用Sql實現分頁)
//介面實現類
public interface StudentMapper{
    
    List<Student> selectStudentByRowBoudns();
    
}
<!--Mapper對映-->
<select id="selectStudentByRowBoudns" resultType="Student">
		select * from 表明
</select>
//Junit測試
public void selectStudentByRowBoudns(){
    //匯入工具類
    MybatisUtils mybatisUtils = new MybatisUtils();
    //建立sqlSession
    SqlSession sqlSession = mybatisUtils.getConnection();
    //新建介面實現類物件
    StudentMapper studnetMapper = sqlSession.getMapper(StudentMapper.class);
    
    try{
        //重點:通過物件實現分頁
        RowBoudns rowBoudns = new RowBounds(1,3)//從第一個開始到第三個結束
        
        List<Student> studentList = sqlSession.selectList("com.xxxx.方法					名",null,rowBoudns);
        /*
        	關於opensession自帶sql語句的引數
			selectList("方法名",Object,RowBounds);        
        */
        studentList.for
            sout(student);
        
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        closeSqlSession(sqlSession);
    }
     
}