MyBaits分页插件-PageHelper

本文介绍MyBatis分页插件PageHelper的使用方法,包括配置步骤和实现原理。PageHelper通过拦截SQL语句实现数据库分页,适用于多种数据库,如Oracle、Mysql等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MySql对分页的支持

MySql对分页的支持是通过limit字句实现的:
Limit [offset,rows]
offset是相对与首行的偏移量(首行是0),rows是返回条数
例如:每页30条数据,取第一页:select * from tableName limit 0,30;
每页30条数据,取第二页:select * from tableName limit 10,30;

由上可知,分页通过limit关键字就可以实现,但是如果项目中用的是MyBatis逆向工程,我们不可能去修改逆向工程的生成的查询语句,此时最好的选择就是MyBatis的分页插件PageHelper。

PageHelper

该插件目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库分页。他的原理是利用Mybatis拦截器,再查询数据库的时候,拦截下sql,然后进行修改,从而实现分页。原理可以用下边一幅图来解释:
这里写图片描述

使用步骤

1、添加pom依赖

<dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
        </dependency>

2、在MyBatis配置文件中进行配置

<!-- 配置分页插件 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- 指定使用的数据库是什么 -->
            <property name="dialect" value="mysql"/>
        </plugin>
    </plugins>

3、分页测试

public class TestPageHelper {

    @Test
    public void testPageHelper() throws Exception{
        //获得mapper代理对象,从spring容器中获得
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
        TbItemMapper itemMapper = applicationContext.getBean(TbItemMapper.class);//查商品列表
        //设置分页
        //只对下边的第一个select有效,再来一个就失效了
        PageHelper.startPage(1, 30);
        //执行查询
        TbItemExample example = new TbItemExample();
        List<TbItem> list = itemMapper.selectByExample(example);
        //取分页后结果
        PageInfo<TbItem> pageInfo = new PageInfo<>(list);
        Long total = pageInfo.getTotal();
        System.out.println("total:"+total);
        int pages = pageInfo.getPages();
        System.out.println("pages:"+ pages);
        int pageSize = pageInfo.getPageSize();
        System.out.println("pageSize:"+ pageSize);
    }
}

结语

就这样,分页功能就实现了。pagehelper的关键就是设置分页的时候,插入“PageHelper.startPage(1, 30);”这句代码,对sql进行编辑,然后执行编辑后的语句。

### Spring Boot 3 中整合 MyBatis-Plus 并实现 MySQL 和 Oracle 数据库分页 #### Maven依赖配置 为了在Spring Boot 3中整合MyBatis-Plus并支持MySQL和Oracle数据库,首先需要引入必要的Maven依赖项。以下是所需的依赖列表: ```xml <dependencies> <!-- Spring Boot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- MyBatis Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.3</version> <!-- 版本号需与Spring Boot兼容 --> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- Oracle JDBC Driver --> <dependency> <groupId>com.oracle.database.jdbc</groupId> <artifactId>ojdbc11</artifactId> <version>21.9.0.0</version> <!-- 使用最新版本 --> <scope>runtime</scope> </dependency> <!-- PageHelper 分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.4.2</version> </dependency> </dependencies> ``` 以上配置涵盖了MyBatis-Plus的核心功能以及针对MySQL和Oracle的支持[^3]。 --- #### 配置 `application.yml` 文件 在Spring Boot应用的根目录下编辑 `application.yml` 文件,分别定义MySQL和Oracle的数据源连接信息,并启用PageHelper分页插件的相关配置。 ```yaml server: port: 8080 spring: datasource: mysql: url: jdbc:mysql://localhost:3306/test_db?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC username: root password: root_password driver-class-name: com.mysql.cj.jdbc.Driver oracle: url: jdbc:oracle:thin:@//localhost:1521/orclpdb1 username: system password: oracle_password driver-class-name: oracle.jdbc.driver.OracleDriver mybatis-plus: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.example.domain pagehelper: helper-dialect: mysql # 默认为MySQL方言 reasonable: true support-methods-arguments: true params: count=countSql ``` 注意:对于不同的数据库(如MySQL和Oracle),可以通过动态数据源切换来管理多个数据库实例[^3]。 --- #### 动态数据源配置 如果希望在同一项目中同时支持MySQL和Oracle,则可以采用动态数据源的方式。通过自定义数据源路由逻辑,可以在运行时决定具体使用的数据库。 ##### 创建动态数据源类 ```java import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; import java.util.HashMap; import java.util.Map; public class DynamicDataSourceConfig { @Bean(name = "mysqlDataSource") @ConfigurationProperties(prefix = "spring.datasource.mysql") public DataSource mysqlDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "oracleDataSource") @ConfigurationProperties(prefix = "spring.datasource.oracle") public DataSource oracleDataSource() { return DataSourceBuilder.create().build(); } @Primary @Bean(name = "dynamicDataSource") public DynamicDataSource dataSource(@Qualifier("mysqlDataSource") DataSource mysqlDataSource, @Qualifier("oracleDataSource") DataSource oracleDataSource) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put("mysql", mysqlDataSource); targetDataSources.put("oracle", oracleDataSource); DynamicDataSource dynamicDataSource = new DynamicDataSource(); dynamicDataSource.setTargetDataSources(targetDataSources); // 添加数据源 dynamicDataSource.setDefaultTargetDataSource(mysqlDataSource); // 设置默认数据源 return dynamicDataSource; } } ``` ##### 自定义抽象父类Mapper接口 为了让MyBatis-Plus能够识别不同数据源下的Mapper接口,建议继承其基础Mapper接口。 ```java @Mapper public interface BaseMapper<T> extends com.baomidou.mybatisplus.core.mapper.BaseMapper<T> { } ``` --- #### 实现分页查询 借助PageHelper插件,可以直接在服务层方法中调用分页功能。以下是一个简单的示例代码片段: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public IPage<User> getUsersByPage(int pageNum, int pageSize) { Page<User> page = new Page<>(pageNum, pageSize); QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.orderByDesc("id"); // 按照ID降序排列 return userMapper.selectPage(page, queryWrapper); } } ``` 上述代码展示了基于MyBatis-Plus内置分页能力的实现方式[^3]。 --- #### 测试与验证 完成上述配置后,启动应用程序并通过API接口测试分页效果。确保MySQL和Oracle两种环境均能正常返回预期的结果集。 ---
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木子松的猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值