7.分页
为什么要分页?
-
因为如果数据过多不分页的话必然会增大服务器内存的负载,降低了系统的运行速度。
mybatis几种分页方式:
7.1 SQL分页
第一步:编写接口和基本的配置文件
//mybatis接口
List<User> findByLimit(Map<String,Object> map)throws Exception;
<!--通过limit查询多个user对象-->
<select id="findByLimit" parameterType="map" resultType="User">
select * from user limit #{currIndex},#{pageSize}
</select>
第二步:编写测试
7.2 RowBounds分页
-
数据量小时,RowBounds不失为一种好办法。但是数据量大时,实现拦截器就很有必要了。
-
相比较sql 更贴近于面向对象
第一步:编写接口
List<User> findByRowBounds()throws Exception;
第二步:编写mapper.xml配置文件sql
<!--通过RowBounds查询多个user对象-->
<select id="findByRowBounds" resultType="User">
select * from user
</select>
第三步:编写测试
-
RowBounds构造方法
public RowBounds(int offset, int limit) {
this.offset = offset;
this.limit = limit;
}
-
SqlSession的selectList方法
/**
* @param parameter 第一个参数方法的全限定类名 Unique identifier matching the statement to use.
* @param parameter A parameter object to pass to the statement.
* @param rowBounds Bounds to limit object retrieval 第三个参数RowBounds对象
* @return List of mapped object
*/
<E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds);
7.3 PageHelper分页插件
-
使用插件的好处就是写起来代码简洁
第一步:导入相关的maven依赖(官网更新到5.1.11)
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.4</version>
</dependency>
第二步:配置拦截器插件(在mybatis-config.xml中配置plugin拦截器插件)(要按照官网顺序)
-
特别注意,新版拦截器是
com.github.pagehelper.PageInterceptor。com.github.pagehelper.PageHelper现在是一个特殊的dialect实现类,是分页插件的默认实现类,提供了和以前相同的用法。
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 使用下面的方式配置参数,后面会有所有的参数介绍 -->
<property name="param1" value="value1"/>
</plugin>
</plugins>
第三步:编写接口和简单的mapper.xml中sql
List<User> findUserByPageHelper()throws Exception;
<!--通过PageHelper查询多个user对象-->
<select id="findUserByPageHelper" resultType="User">
select * from user
</select>
第四步:编写测试代码

浙公网安备 33010602011771号