mybatis分页插件PageHelper的简单使用

插件叫做PageHelper如果你也在用Mybatis,建议尝试该分页插件,这个一定是最方便使用的分页插件。

该插件目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库分页。

使用方法:

第一步:导入mybatis的分页jar包。(两个jar包)

第二步:需要在SqlMapConfig.xml,配置一个plugin。

第三步:在sql语句执行之前,添加一个PageHelper.startPage(page,rows);

第四步:取分页结果。创建一个PageInfo对象需要参数,查询结果返回的list。从PageInfo对象中取分页结果。

一、导入jar包

二、修改SqlMapConfig.xml

 

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEconfiguration
		PUBLIC"-//mybatis.org//DTD Config 3.0//EN"
		"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

	<!-- 配置分页插件 -->
	<plugins>
		<plugininterceptor="com.github.pagehelper.PageHelper">
			<!-- 指定使用的数据库是什么 -->
			<propertyname="dialect"value="mysql"/>
		</plugin>
	</plugins>

</configuration>

三、​​​​​​​代码测试

publicclass TestPageHelper {
	
	@Test
	publicvoid testPageHelper() throws Exception {
		//1、获得mapper代理对象
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
		TbItemMapper itemMapper = applicationContext.getBean(TbItemMapper.class);
		//2、设置分页
		PageHelper.startPage(1, 30);
		//3、执行查询
		TbItemExample example = new TbItemExample();
		List<TbItem>list = itemMapper.selectByExample(example);
		//4、取分页后结果
		PageInfo<TbItem>pageInfo = new PageInfo<>(list);
		longtotal = pageInfo.getTotal();
		System.out.println("total:" + total);
		intpages = pageInfo.getPages();
		System.out.println("pages:" + pages);
		intpageSize = pageInfo.getPageSize();
		System.out.println("pageSize:" + pageSize);
		
	}

}

猜你喜欢

转载自blog.csdn.net/hsw201508130017/article/details/85005094