前言
Don’t Repeat Yourself,在之前几个项目中,在使用mybatis做分页时,一直使用自定义page分页工具类,工具类中包含了
//当前页码
private Integer page;
//页展示条目数
private Integer rows= 10;
//开始
private Integer startWith;
//结束
private Integer endWith;
几个参数,在进行分页查询时,需要执行count语句计算分页信息,在将计算好的分页信息作为sql查询语句的参数,除了麻烦之外,还存在着重复的问题,空闲(划水)时候了解了一下pagehelper分页组件,不仅能省去很多代码,而且还支持目前所有类型的数据库
一、pom文件引入
这里有个需要注意的地方,pagehelper4.0以下版本对sqlservr的语法不支持(也可能是自己写法的问题,没有深入的去看,把版本改为4.0就可以了)。
pom文件引入 内联代码片
。
<!--pagehelper分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9.1</version>
</dependency>
pom文件引入 内联代码片
。
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 方言, value为数据库类型,4.0以上版本不需要引入该注解,会自动识别-->
<!--<property name="dialect" value="sqlservr"/>-->
<!-- 设置为true时,使用RowBounds分页会进行count查询 -->
<property name="rowBoundsWithCount" value="true"/>
</plugin>
二、测试
dao
List<UserInfo> queryUserListLikeName(@Param("name") String name);
mapper
<select id="queryUserListLikeName" resultType="cn..user.UserInfo" parameterType="String">
SELECT cPersonName FROM person order by iuPkId
</select>
测试类
@Test
public void testQueryUserListLikeName() {
//设置分页条件,Parameters:pageNum 页码pageSize 每页显示数量count 是否进行count查询
PageHelper.startPage(3, 1, true);
List<UserInfo> users = userDao.queryUserListLikeName(null);
for (UserInfo user : users) {
System.out.println(user);
}
}
执行结果
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@45fd9a4d] was not registered for synchronization because synchronization is not active
JDBC Connection [ConnectionID:2] will not be managed by Spring
ooo Using Connection [ConnectionID:2]
> Preparing: SELECT count(*) FROM person
> Parameters:
< Columns:
< Row: 3
<== Total: 1
ooo Using Connection [ConnectionID:2]
> Preparing: SELECT TOP 1 cPersonName FROM (SELECT ROW_NUMBER() OVER ( ORDER BY iuPkId) PAGE_ROW_NUMBER, cPersonName FROM person) AS PAGE_TABLE_ALIAS WHERE PAGE_ROW_NUMBER > 2 ORDER BY PAGE_ROW_NUMBER
> Parameters:
< Columns: cPersonName
< Row: sherL
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@45fd9a4d]
UserInfo{iuPkId=null, cPersonName=‘sherL’, cPassWord=‘null’, cStatus=null, cDepCode=‘null’, cPosition=‘null’, cPersonEmail=‘null’, cPersonPhone=‘null’, cCreator=‘null’, dCreatTime=null, cModifier=‘null’, dModifyTime=null, cMemo=‘null’, cusDefine1=‘null’, cusDefine2=‘null’, cusDefine3=‘null’, cusDefine4=‘null’, cusDefine5=‘null’}
总结
可以看到,在引入了pagehelper分页插件后,不需要自己写page分页方法去查询count以及传入分页参数,pagehelper会自动完成该操作.