原博主:http://blog.csdn.net/appleyk/article/details/77318175 感谢appleyk博主最开始我的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>
- <!-- 配置分页插件 PageHelper -->
- <plugins>
- <plugin interceptor="com.github.pagehelper.PageHelper">
- </plugin>
- </plugins>
- </configuration>
后面还有一行关键描述:
Cause: java.lang.ClassCastException: com.github.pagehelper.PageHelper cannot be cast to org.apache.ibatis.plugin.Interceptor
意思就是说这个分页插件的Interceptor没有被实现
来看一下我的,PageHelper版本,以及com.github.pagehelper.PageHelper类
pageHelper是如何在mybatis中工作呢,是通过mybatis的pulgin实现了Interceptor接口,从而获得要执行的sql语句实现分页技术,而我们的PageHelper5.0.0版本中的这个类,并没有出现implements Interceptor,我们再来看下pagehelper这个包下的其他类,我们发现,有个类很像我们要的,我们进去一看,果然是它:
因此,我们修改我们的mybatis全局配置文件SqlMapConfig.xml如下:
再次,运行如下:
这个会话工程"sqlSessionFactory"怎么又出来了,我们往后翻,发现有个关键描述:
Error parsing SQL Mapper Configuration. Cause: com.github.pagehelper.PageException: java.lang.ClassNotFoundException: mysql
没有发现mysql这个类,太折腾了,我也不想检查其他jar包是否版本不对了,这个后面有时间再去研究,网上说,PageHelper插件4.0.0以后的版本支持自动识别使用的数据库,可以不用配置 <property name="dialect" value="mysql"/>
ok,没问题了,项目正常跑起来了
接着是测试:
package com.github.pagehelper;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.xy.video.bean.User;
import com.xy.video.bean.UserExample;
import com.xy.video.dao.UserMapper;
public class TestPageHelper {
/**
* @throws Exception
* 2017年8月17日12:00:57
*/
@Test
public void testPageHelper() throws Exception{
//1、获得mapper代理对象
//初始化一个spring容器
ApplicationContext applicationContext = null;
try{
//获得spring上下文对象
applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}
catch (Exception ex) {
ex.printStackTrace();
}
//拿到一个代理对象 我们要操作的商品信息 在mapper映射类中,我们通过上下文对象拿到这个类的代理
UserMapper bean = applicationContext.getBean(UserMapper.class);
//2、设置分页处理
PageHelper.startPage(1, 20);//每页显示20条 相当于 SELECT * FROM taotao.tb_item limit 0,20;
//3、执行查询
UserExample example = new UserExample();
//Criteria criteria = example.createCriteria();
//criteria.andIdEqualTo(value) //这个是根据某个条件查 比如主键商品ID
List<User> list = bean.selectByExample(example);//example不设置 表示无条件 这个时候bean已经将分页效果(sql语句)作用在example上了
if(list != null & list.size()>0){
int i = 0;
for(User item : list){
System.out.println(item.getUserName()+","+(i+1));//输出商品的标题,一页20行
i++;
}
}
//4、取分页后的结果
//包装list
PageInfo<User> pageInfo = new PageInfo<>(list);
long total = pageInfo.getTotal();//总记录数
System.out.println("total:"+total);
int pages = pageInfo.getPages();
System.out.println("pages:"+pages);//总页数
int pageSize= pageInfo.getPageSize();
System.out.println("pageSize:"+pageSize);//每页的展示数
}
}