在已经集成Mybatis的项目中集成分页插件Pagehelper
1、在pom.xml中添加Pagehelper依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
2、分页插件配置
在application.yml配置文件中增加以下配置信息:
pagehelper:
helperDialect: oracle
reasonable: true
supportMethodsArguments: true
params: count=countSql
3、简单使用(分页查询歌曲信息)
xml配置:
<!--分页查询歌曲信息-->
<select id="querySongsByPage" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from SONG song
<where>
<include refid="queryWhere"/>
</where>
<include refid="orderBy"/>
</select>
dao层接口:
@Mapper
public interface SongEntityMapper extends MyMapper<SongEntity> {
// 条件分页查询
List<SongEntity> querySongsByPage(@Param("songRequest") SongRequest songRequest);
// 查询总条数
Long getTotalSongByParam(@Param("songRequest") SongRequest songRequest);
}
服务层方法:
@Override
public Object querySongsByPage(SongRequest songRequest) {
// 在调用查询接口的上一行添加PageHelper.startPage方法
PageHelper.startPage(songRequest.getCurrentpage() - 1, songRequest.getMaxresult());
List<SongEntity> songs = songMapper.querySongsByPage(songRequest);
Long total = songMapper.getTotalSongByParam(songRequest);
// ...
}
为什么在添加了startPage方法之后就能实现分页查询呢?这里可以简单说一下原理。
分析源码可知,startPage里面赋值的分页参数会转换成Page对象,保存在一个本地线程变量ThreadLocal里面。
protected static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal<Page>();
在最后执行查询的时候利用mybatis提供的拦截器,取得ThreadLocal里保存的分页参数值,重新拼装分页SQL,完成分页。