本文源码:Gitee·点这里
MyBatisPlus有现成的分页功能,需要将插件添加到配置中
配置分页插件
@Configuration
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则
*
* @return
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
分页查询并排序
@Test
public void testSelectPage() {
Page<User> page = new Page<>(3, 3);
page.addOrder(OrderItem.asc("age"));
Page<User> userPage = userMapper.selectPage(page, null);
System.out.println("总条数:" + userPage.getTotal());
System.out.println("当前页数:" + userPage.getCurrent());
System.out.println("每页大小:" + userPage.getSize());
System.out.println("当页大小:" + userPage.getRecords().size());
System.out.println(userPage.getRecords());
}
执行日志:
JDBC Connection [HikariProxyConnection@1347294617 wrapping com.mysql.cj.jdbc.ConnectionImpl@71f96dfb] will not be managed by Spring
==> Preparing: SELECT COUNT(1) FROM user
==> Parameters:
<== Columns: COUNT(1)
<== Row: 8
<== Total: 1
==> Preparing: SELECT id, name, age, email FROM user ORDER BY age ASC LIMIT ?,?
==> Parameters: 6(Long), 3(Long)
<== Columns: id, name, age, email
<== Row: 4, Sandy, 21, test4@baomidou.com
<== Row: 3, Tom, 28, test3@baomidou.com
<== Total: 2
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@cb0f763]
总条数:8
当前页数:3
每页大小:3
当页大小:2
[User{id=4, name='Sandy', age=21, email='test4@baomidou.com'}, User{id=3, name='Tom', age=28, email='test3@baomidou.com'}]
通过日志可以看出,
- 通过
SELECT COUNT(1) FROM user
查询出总页数 - 并先排序再通过limit分页查询
网友评论