Mybatis分页插件快速入门

分页插件:

分页插件:独立于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);
        }
    }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值