mybatis使用逆向工程时分页插件的使用

一、使用场景

查询的表:tb_item

单表查询sqlSELECT * from tb_itemLIMIT 0,10

需要实现分页,使用逆向工程,可以使用mybatis的分页插件。

二、原理 

 

 三、使用方法

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

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

使用方法:

第一步:添加jar包

		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>${pagehelper.version}</version>
		</dependency>

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

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

第三步:在sql语句执行之前,添加一个PageHelper.startPage(page,rows);
第四步:取分页结果。创建一个PageInfo对象需要参数,查询结果返回的list。从PageInfo对象中取分页结果。

四、测试

public class TestPageHelper {
	
	@Test
	public void 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);
		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);
		
	}

}


猜你喜欢

转载自blog.csdn.net/u012184337/article/details/67637115
今日推荐