一、准备
- 编辑工具:IDEA
- 我的项目路径:
- 插件地址:https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper/5.1.8
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.8</version> </dependency>
二、配置MyBatis的全局配置SqlMapConfig.xml文件
<?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> <!--配置分页插件--> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!--PageHelper插件4.0.0以后的版本支持自动识别使用的数据库,所以下面这个属性不需要写--> <!--<property name="dialect" value="mysql"/>--> </plugin> </plugins> </configuration>
三、在文件applicationContext-dao.xml中整合MyBatis
<!--整合MyBatis--> <!--让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 加载mybatis的全局配置文件 --> <property name="configLocation" value="classpath:mybaits/SqlMapConfig.xml"/> </bean> <!--mybatis扫描dao层--> <bean id="mappers" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <property name="basePackage" value="cn.e3mall.mapper" /> </bean> </beans>
四、在src/test/java/cn.e3mall.pagehelper中创建测试类PageHelperTest.java
package cn.e3mall.pagehelper; import cn.e3mall.mapper.TbItemMapper; import cn.e3mall.pojo.TbItem; import cn.e3mall.pojo.TbItemExample; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; public class PageHelperTest { @Test public void testPageHelper() { //初始化spring容器 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml"); //从容器中获得mapper代理对象 TbItemMapper itemMapper = applicationContext.getBean(TbItemMapper.class); //执行SQL语句之前设置分页信息使用PageHelper的startPage方法 PageHelper.startPage(1, 10); //执行查询 TbItemExample example=new TbItemExample(); List<TbItem> list = itemMapper.selectByExample(example); //取分页信息,PageInfo:总记录数,总页数,当前页码 PageInfo<TbItem> pageInfo=new PageInfo<>(list); //总记录数 System.out.println(pageInfo.getTotal()); //记录总页数 System.out.println(pageInfo.getPages()); //每页的信息数 System.out.println(list.size()); } }