1. 程式人生 > >MyBatis實現分頁

MyBatis實現分頁

本案例以上一章Spring整個MyBatis案例為基礎

集合分頁(未使用SQL分頁:假分頁)

原理:在進行sql查詢時一次性查詢到所有資料儲存在list中,再使用subList獲取滿足條件的記錄。這種方法也被稱為假分頁。 此方法適用於資料量較少的情況下,當資料量資料量較大時會影響資料庫以及伺服器的效能。 本案例附帶條件查詢,模糊查詢為例

StudentMapper介面中定義page方法

/**
 * 
 * @param student
 * @return
 */
List<Student> page(Student student);

StudentMapper.xml對映檔案中實現

<select id="page" parameterType="student" resultType="student">
	select  student_id studentId,name studentName,age,grade_id gradeId
	from `student` 
	<where>
		<if test="studentId!=null">
			and student_id=#{studentId}
		</if>
		<if test="studentName!=null">
			and `name` like '%${studentName}%'
		</
if
>
</where> </select>

新建StudentService業務層

@Service
public class StudentService {
	@Autowired
	private StudentMapper studetnMapper;
	public List<Student> page(Student student,int currentPage,int pageSize){
		List<Student> students=studetnMapper.page(student);
		//通過得到集合中指定的元素來實現分頁
return students.subList((currentPage-1)*pageSize, pageSize); } }

測試:

@Test
public void testPage(){
	ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
	StudentService stuService=ctx.getBean("studentService",StudentService.class);
	List<Student> stus=stuService.page(new Student(), 1, 2);
	System.out.println(stus);
}

測試結果,從第1條開始輸出了2條:

[Student [studentId=1, studentName=張三, age=12, gradeId=1], Student [studentId=2, studentName=李四, age=12, gradeId=2]]

SQL分頁(真分頁)

使用SQL分頁需要傳本來需要的條件引數Student與分頁引數currentPage和pageSize,這裡為了在對映檔案中做處理,我們傳入一個map集合作為引數,首先修改StudentMapper介面中的方法:

/**
 * @param map
 * @return
 */
List<Student> page(Map<String,Object> map);

然後修改mapper.xml對映檔案:

<select id="page" parameterType="map" resultType="student">
select  student_id studentId,name studentName,age,grade_id gradeId
	from `student` 
	<where>
		<if test="student.studentId!=null">
			and student_id=#{student.studentId}
		</if>
		<if test="student.studentName!=null">
			and `name` like '%${student.studentName}%'
		</if>
	</where>
	limit #{fromIndex},#{pageSize}
</select>

修改業務層程式碼,在業務層做分頁引數的處理:

public List<Student> page(Student student,int currentPage,int pageSize){
	Map<String, Object> map=new HashMap<String, Object>();
	map.put("fromIndex", (currentPage-1)*pageSize);
	map.put("pageSize", pageSize);
	map.put("student", student);
	List<Student> students=studetnMapper.page(map);
	//通過得到集合中指定的元素來實現分頁
	return students;
}

測試上述方法,結果一樣。 此方法實現了要求,獲取到了指定的資料,但是每次在分頁時都需要編寫limit語句,不方便統一管理,維護性較差。所以我們可以使用更方便的分頁實現。

使用攔截器實現分頁

–暫略

使用RowBounds分頁

–暫略