在MyBatis-Plus中,分页功能通常是通过配置MybatisPlusInterceptor(或其前身PaginationInterceptor)来实现的,这是一个全局的拦截器,用于拦截MyBatis的SQL执行,并在其中添加分页逻辑。以下是一个使用MybatisPlusInterceptor进行分页查询的案例:
- 添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
- 配置Mapper接口
@Mapper
public interface BookDao extends BaseMapper<Book> {
}
- 配置MybatisPlusInterceptor
package com.atheima.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MPConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
// 添加分页插件
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
// 如果有其他插件,可以继续添加
// interceptor.addInnerInterceptor(...);
return mybatisPlusInterceptor;
}
}
注意:从MyBatis-Plus 3.4.0开始,PaginationInterceptor被重命名为PaginationInnerInterceptor,并且需要作为MybatisPlusInterceptor的一个内部拦截器来添加。
4. 使用分页API进行查询
在Service或Mapper接口中,使用MyBatis-Plus提供的IPage
@Autowired
private BookDao bookDao;
public IPage selectUserPage(int currentPage, int pageSize) {
// 创建分页对象
Page page = new Page(currentPage, pageSize);
// 调用Mapper接口方法进行分页查询
return bookDao.selectPage(page, null); // null表示没有查询条件
// 返回分页结果
}
- 测试
@Autowired
private BookService bookService;
@Test
public void testGetPage2(){
bookService.selectUserPage(1,6);
}
标签:拦截器,分页,boot,查询,MybatisPlusInterceptor,plus,com,public
From: https://www.cnblogs.com/DuWenjie/p/18322474