在 Spring Boot 项目中使用分页插件的两种常见方式

在 Spring Boot 项目中使用分页插件主要有两种常见方式:使用 MyBatis-Plus 的分页插件和使用 PageHelper 插件。以下是两种方式的详细使用方法:

使用 MyBatis-Plus 分页插件

1. 添加依赖pom.xml 文件中添加 MyBatis-Plus 的依赖:

复制代码
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>版本号</version>
</dependency>

2. 配置分页插件 创建一个配置类,添加分页插件的配置:

复制代码
@Configuration
@MapperScan("scan.your.mapper.package")
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

3. 使用分页功能 在 Service 层中,使用 Page 类进行分页查询:

复制代码
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public IPage<User> getUserPage(int current, int size) {
        Page<User> page = new Page<>(current, size);
        return userMapper.selectPage(page, null);
    }
}

使用 PageHelper 分页插件

1. 添加依赖pom.xml 文件中添加 PageHelper 的依赖:

复制代码
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>版本号</version>
</dependency>

2. 配置 PageHelperapplication.yml 文件中配置 PageHelper:

复制代码
pagehelper:
  helperDialect: mysql
  reasonable: true

3. 使用分页功能 在 Service 层中,使用 PageHelper 进行分页查询:

复制代码
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public PageInfo<User> getUserPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.list();
        return new PageInfo<>(users);
    }
}

两种分页插件各有优势,MyBatis-Plus 的分页插件与 MyBatis-Plus 的 CRUD 接口无缝集成,使用简单;PageHelper 则是一个独立的分页插件,支持多种数据库,且分页逻辑与 Mapper 层解耦,使用灵活。你可以根据项目需求选择合适的分页插件。

相关推荐
东风破_4 小时前
ESLint 是什么?为什么你的项目需要它?
前端·后端·代码规范
嘻哈∠※4 小时前
0061基于 SpringBoot 的投稿与稿件处理系统设计与实现
java·spring boot·后端
卷无止境5 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
白狐_7985 小时前
408数据结构第8章:排序②——性质对比秒杀、场景选择与外部排序
java·数据结构·算法
zander2586 小时前
LeetCode 84:柱状图中的最大矩形——单调栈如何确定左右边界
java·数据结构·算法
码匠许师傅6 小时前
【C++ 面试真题】聊聊 C++ 的拷贝构造与拷贝赋值
java·c++·面试
卷无止境6 小时前
FastAPI 的Admin面板生态
后端·python
捡田螺的小男孩7 小时前
什么是 Skill?手把手带你写一个简单有用的 Skill!
前端·后端·程序员
IT_陈寒7 小时前
Redis集群这个坑,差点让我通宵
前端·人工智能·后端
极创信息7 小时前
系统安全隐患全方位排查方案:标准化渗透测试全流程
java·opencv·struts·数据挖掘·eclipse·语音识别·hibernate