如果你也在用Mybatis,建议尝试该分页插件,这个一定是最方便使用的分页插件。
该插件目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库分页。
我在做项目时在Mybatis配置xml中配置拦截器插件如下:
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
运行时却出现错误,报错:
java.lang.ClassCastException: com.github.pagehelper.PageHelper cannot be cast to org.apache.ibatis.plugin.Interceptor
pageHelper是如何在mybatis中工作呢,是通过mybatis的pulgin实现了Interceptor接口,从而获得要执行的sql语句实现分页技术,而我们的PageHelper5.1.2版本中的这个类,并没有出现实现拦截器
然而我们的PageHelper类中,并没有拦截器:
public class PageHelper extends PageMethod implements Dialect {
private PageParams pageParams;
private PageAutoDialect autoDialect;
public PageHelper() {
}
......
}
因此,我们需要修改我们的mybatis全局配置文件SqlMapConfig.xml如下:
<configuration>
<!-- 配置分页插件 PageHelper -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
</configuration>
再次运行时出现错误:
Cause: com.github.pagehelper.PageException: java.lang.ClassNotFoundException: mysql
这是因为在pagehelper插件4.0.0以后的版本支持自动识别使用的数据库,可以不用配置数据库方言
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>
这次运行时就能够成功。