今天在使用pagehelper将信息进行分页的时候遇到了很多的问题,始终不能分页成功,现在将问题以及解决办法总结。
使用步骤
1、在pom中导入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.4</version>
</dependency>
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>
<!-- 引入分页插件 -->
<!-- 要求3.3版本以上的mybatis -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 分页参数合理化,即不可能到达-1页之类不合理的页数 -->
<property name="reasonable" value="true"/>
</plugin>
</plugins>
</configuration>
3、不要忘记在你的spring的配置文件中加载mybatis 的配置文件
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
</bean>
4、编写测试方法
PageHelper.startPage(start,rows);只对他之后的第一条查询语句进行分页
@Test
public void testPageHelper() throws Exception {
//初始化spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
//从容器中获得Mapper代理对象
BArticlesMapper bArticlesMapper = (BArticlesMapper) applicationContext.getBean(BArticlesMapper.class);
//执行sql语句之前设置分页信息使用PageHelper的startPage方法。
//设置现在的页数为2,显示的条数为5条
PageHelper.startPage(2, 5);
List<BArticles> list = bArticlesMapper.selectByExampleWithBLOBs(null);
System.out.println(list.size());
//取分页信息,PageInfo。
PageInfo<BArticles> pageInfo = new PageInfo<>(list);
System.out.println("当前页码"+pageInfo.getPageNum());
System.out.println("总页码"+pageInfo.getPages());
System.out.println("总记录数"+pageInfo.getTotal());
//取得分页之后的单页的信息
List<BArticles> list2 = pageInfo.getList();
}