1.limit分页
mysql的limit后⾯两个数字:
第⼀个数字:startIndex(起始下标。下标从0开始。)
第⼆个数字:pageSize(每⻚显示的记录条数)
假设已知⻚码pageNum,还有每⻚显示的记录条数pageSize,第⼀个数字可以动态的获取吗?
startIndex = (pageNum - 1) * pageSize
所以,标准通⽤的mysql分⻚SQL:
select * from tableName ...
limit (pageNum - 1) * pageSize, pageSize
2.使⽤mybatis分页
CarMapper接口
List<Car> selectAllByPage(@Param("startIndex") Integer startIndex,
@Param("pageSize") Integer pageSize);
CarMapper.xml
<select id="selectAllByPage" resultType="Car">
select * from t_car limit #{startIndex},#{pageSize}
</select>
3. PageHelper插件的使用
第一步:引入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.2</version>
</dependency>
第二步:在mybatis-config.xml中配置插件
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
第三步:编写Java代码
@Test
public void testPageHelper() throws Exception {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
// 开启分⻚
PageHelper.startPage(2, 2);
// 执⾏查询语句
List<Car> cars = mapper.selectAll();
// 获取分⻚信息对象
PageInfo<Car> pageInfo = new PageInfo<>(cars, 5);
System.out.println(pageInfo);
/*
PageInfo{pageNum=2, pageSize=2, size=2, startRow=3, endRow=4, total=15, pages=8,
list=Page{count=true, pageNum=2, pageSize=2, startRow=2, endRow=4, total=15, pages=8, reasonable=false, pageSizeZero=false}
[Car{id=4, carNum='1003', brand='丰田霸道', guidePrice=32.00, produceTime='2001-10-11', carType='燃油车'},
Car{id=5, carNum='1003', brand='丰田霸道', guidePrice=33.00, produceTime='2002-10-11', carType='燃油车'}],
prePage=1, nextPage=3, isFirstPage=false, isLastPage=false, hasPreviousPage=true, hasNextPage=true,
navigatePages=5, navigateFirstPage=1, navigateLastPage=5, navigatepageNums=[1, 2, 3, 4, 5]}
*/
}