目录
一.分页的原理
二.Mybatis实现
三.PageHelper
第⼀步:引⼊依赖
第⼆步:在mybatis-config.xml⽂件中配置插件
第三步:编写Java代码
一.分页的原理
pageindex 页数 pagindex 页内数据
(pageindex-1)*pagesize,pagesize
SELECT * FROM table LIMIT(PageNo - 1)*PageSize, PageSize;
二.Mybatis实现
测试程序 就全查出来 然后分页int pageIndex = 1;pageIndex = (pageIndex - 1) * pageSize;List<Employee> employees = mapper.queryEmployeeByPage(pageIndex, pageSize);
List<Employee> queryEmployeeByPage(@Param("pageindex") int pageindex, @Param("pagesize")int pageSize);
三.PageHelper
第⼀步:引⼊依赖
pom.xml
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper --> <dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.3.3</version> </dependency>
第⼆步:在mybatis-config.xml⽂件中配置插件
typeAliases标签下⾯进⾏配置:
<plugins><plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin></plugins>
第三步:编写Java代码
关键点:PageHelper.startPage(pageIndex,pageSize); //开启分页
PageInfo<Car> pageInfo = new PageInfo<>(cars, 5); 获取分页信息
在查询语句之前开启分⻚功能。
在查询语句之后封装PageInfo对象。(PageInfo对象将来会存储到request域当中。在⻚⾯上展 示。)
//开启分页int pageNum=2;int pageSize=4;PageHelper.startPage(pageNum,pageSize);// 执⾏查询语句List<Car> cars = mapper.queryCarList();cars.forEach(new Consumer<Car>() {@Overridepublic void accept(Car car) {System.out.println(car);}});// 获取分⻚信息对象PageInfo<Car> pageInfo = new PageInfo<>(cars, 5);System.out.println(pageInfo);
四关于sqlSession 线程代码
public class SqlSessionUtil {static ThreadLocal<SqlSession> sqlSessionThreadLocal = new InheritableThreadLocal<>();static SqlSession sqlSession;static {SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();try {InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");SqlSessionFactory build = sqlSessionFactoryBuilder.build(inputStream);sqlSession = build.openSession(false);sqlSessionThreadLocal.set(sqlSession);} catch (IOException e) {throw new RuntimeException(e);}}public static SqlSession getSqlSession() {return sqlSession;}public static void close(SqlSession sqlSession) {if (sqlSession != null) {sqlSession.close();}sqlSessionThreadLocal.remove();}