> 文章列表 > mybatis分页插件的详细理解和使用

mybatis分页插件的详细理解和使用

mybatis分页插件的详细理解和使用

mybatis分页插件的基本理解和使用

为什么要使用mybatis分页插件?

分页是一种将所有数据分段展示给用户的技术。用户每次看到的不是全部数据,而是其中一部分,如果在其中没有找到自己想要的内容,用户可以通过制定页码或者是翻页的方式转换可见内容,直到找到自己想要的内容为止。

分页的好处:

1、分页能提高性能,一次查20个和一次性查询2000个的性能肯定更好;其次就是如果数据量很庞大,一次性将内容查询出来,查询出来的结果是放在内存里面的,会增加cpu的开销造成内存的浪费,效率极为低。

2、为了展现层考虑:如果一次展现太多,不管是排版和美观上都不是很好。

下面根据示例来理解分页插件的使用:

在pom.xml引入分页插件

		<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.1.10</version></dependency>

在config文件中配置分页(放在environments之前)

<!--    配置分页--><plugins><plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin></plugins>

在StudentMapper接口中定义方法

List<Student> getAllStudent();

在StudentMapper配置中添加内容

<select id="getAllStudent" resultType="Student" useCache="true">select * from student</select>

测试:

@Testpublic void t03(){//设置当前页码及每页显示条数PageHelper.startPage(1,2);SqlSession sqlSession = sqlSessionUtil.getSqlSession();StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);List<Student> list = studentMapper.getAllStudent();//从查到的数据中取到当页数据,生成pageInfo对象PageInfo<Student> pageInfo = new PageInfo<>(list);//获取当页数据List<Student> studentList = pageInfo.getList();//遍历输出当前页的所有数据studentList.forEach(System.out::println);//总数据条数long total = pageInfo.getTotal();System.out.println("总数据条数有:"+total);//总页数int totalPage = pageInfo.getPages();System.out.println("总页数有:"+totalPage);sqlSession.close();}

运行结果:

在这里插入图片描述