山东省建设科技协会网站搜索网页内容
1.limit分页
limit分页原理
mysql的limit后面两个数字:
第一个数字:startIndex(起始下标。下标从0开始。)
第二个数字:pageSize(每页显示的记录条数)
假设已知页码pageNum,还有每页显示的记录条数pageSize,第一个数字
startIndex = (pageNum - 1) * pageSize
所以,标准通用的mysql分页SQL:
select *
from tableName ......
limit (pageNum - 1) * pageSize, pageSize
2. PageHelper插件
使用PageHelper插件进行分页,更加的便捷。
第一步:引入依赖
<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.3.1</version>
</dependency>
第二步:在mybatis-config.xml文件中配置插件
<!--mybatis分页的拦截器-->
<plugins><plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
第三步:编写Java代码
关键点:
- 在查询语句之前开启分页功能。
- 在查询语句之后封装PageInfo对象。(PageInfo对象将来会存储到request域当中。在页面上展示。)
@Test
public void testSelectAll(){SqlSession sqlSession = SqlSessionUtil.openSession();CarMapper mapper = sqlSession.getMapper(CarMapper.class);// 在执行DQL语句之前,开启分页功能//查询第二页,前三条记录int pageNum = 2;int pageSize = 3;PageHelper.startPage(pageNum, pageSize);List<Car> cars = mapper.selectAll();cars.forEach(car -> System.out.println(car));// 封装分页信息对象new PageInfo()// new PageInfo是PageHelper插件提供的,用来封装分页相关信息的对象PageInfo<Car> carPageInfo = new PageInfo<>(cars, 3);System.out.println(carPageInfo);/*PageInfo{pageNum=2, pageSize=3, size=3, startRow=4, endRow=6, total=17, pages=6,list=Page{count=true, pageNum=2, pageSize=3, startRow=3, endRow=6, total=17, pages=6, reasonable=false, pageSizeZero=false}[Car{id=6, carNum='1003', brand='丰田霸道', guidePrice=30.00, produceTime='2000-10-11', carType='燃油车'},Car{id=7, carNum='1003', brand='丰田霸道', guidePrice=30.00, produceTime='2000-10-11', carType='燃油车'},Car{id=8, carNum='1003', brand='丰田霸道', guidePrice=30.00, produceTime='2000-10-11', carType='燃油车'}],prePage=1, nextPage=3, isFirstPage=false, isLastPage=false, hasPreviousPage=true, hasNextPage=true,navigatePages=3, navigateFirstPage=1, navigateLastPage=3, navigatepageNums=[1, 2, 3]}*/sqlSession.close();
}