为公司的网站开发了一个简单的任务管理系统,使用的是mybatis,无疑,分页是真的麻烦,写的想吐,就在GitHub上找了这个分页插件,pagehelper。完了之后不会用,就去找各位大佬用过的代码,看起来真的很简单,结果我搞了两三个小时都分不了页,终于在一位大佬那里找到了原因,仅作为经验记录下来。有错欢迎指正,不喜勿喷!
集成很简单,总共就分为三步:
第一,maven依赖(如果不是maven项目,可以自己去下载jar包)
在进行maven依赖时,各位大佬都提到了一定要注意jar包版本的匹配,在一位大佬博客扒了一套可行性方案,mybatis 3.2.8,pagehelper 5.0.2,jsqlparser 0.9.5,依赖如下
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.2</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9.5</version>
</dependency>
第二、将pagehelper与spring进行集成,有两种方式,一种是直接与spring集成,一种是配置在mybatis的配置文件里面,
1、spring集成
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置datasource -->
<property name="dataSource" ref="dataSource" />
<!-- 配置DomainMapper.xml -->
<property name="mapperLocations" value="classpath*:com/p2p/mapper/*.xml" />
<!-- 配置别名 -->
<property name="typeAliasesPackage" value="com.p2p.domain" />
<!-- 配置分页插件 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<value>
helperDialect=mysql
reasonable=true
autoRuntimeDialect=true
</value>
</property>
</bean>
</array>
</property>
</bean>
在applicationContext.xml文件中加入配置分页插件那一段就可以了,千万记住bean里面的class等于com.github.pagehelper.PageInterceptor,之前我抄大佬的代码可能是因为版本问题,他们都是com.github.pagehelper.PageHelper
发现这个问题多亏了这个大佬的博客 http://blog.csdn.net/wzyxdwll/article/details/66473466
2、mybatis集成
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置mybatis的分页插件PageHelper -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>
</configuration>
因为我是用spring集成的,这是额外写的一个mybatis的核心配置文件,如果有核心配置文件,把plugins那一段加上就可以了,最后在applicationContext-mvc.xml文件里面引入mybatis的配置文件
第三、验证分页,service层什么的就不贴了
看下接口和效果
有一点一定要注意就是获取数据的代码一定是在调用startPage的下一行,才能进行有效的分页