分页插件:
分页插件:独立于MyBatis之外的第三方插件
1.添加依赖:
首先添加分压插件的依赖 —— PageHelper
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
2.配置插件:
在MyBatis的主配置文件中mybatis-config.xml 中通过 plugins标签进行配置,注意标签的位置
<!-- plugins主要用于配置MyBatis插件,例如分页插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
3.分页实例:
对数据库信息进行分页查询(以学生信息为例)
@Test
public void testGetStudentByPage() throws IOException {
StudentDAO studentDAO = MyBatisUtil.getMapper(StudentDAO.class);//sqlSession
PageHelper.startPage(1,4);//分页,从第1页开始,往后的4条数据
List<Student> studentList = studentDAO.listStudents();//查全量就可以,分页组件会自动将数据进行分页
PageInfo<Student> pageInfo = new PageInfo<Student>(studentList);
//返回的时候只需要将pageInfo 返回就可以,因为pageInfo中就包含了分页以及数据信信息
}
4.带条件的分页:
public interface StudentDAO {
public List<Student> listStudentsByGender(String gender);
}
<select id="listStudentsByGender" resultMap="studentMap">
select <include refid="sqlpianduan"/>
from tb_students where stu_gender = #{stuGender}
</select>
@Test
public void testGetStudentByPageGender() throws IOException {
StudentDAO studentDAO = MyBatisUtil.getMapper(StudentDAO.class);
PageHelper.startPage(1,4);
List<Student> girls = studentDAO.listStudentsByGender("女");
PageInfo<Student> pageInfo = new PageInfo<Student>(girls);
//pageInfo中就包含了分页以及数据信息
for(Student s : pageInfo.getList()){
System.out.println(s);
}
}