springboot集成pageHelper实现分页查询

1.新建springBoot项目,在pom.xml中导入对应得依赖
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>
<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>3.3.2</version>
</dependency>
<dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper</artifactId>
  <version>4.2.1</version>
</dependency>
<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-annotation</artifactId>
  <version>3.3.2</version>
</dependency>
 
2.在application.properties中配置数据库连接
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://ip:port/dbName?serverTimezone=Asia/Shanghai&characterEncoding=utf8&allowMultiQueries=true
spring.datasource.username=xxx
spring.datasource.password=xxxx

3.给mybatisPlus配置pageHelper插件
package com.example.demo.common.mybatis;
 
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
import java.util.Properties;
 
/**
* @version 1.0
* @date: 2021-06-16 17:31
*/
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
  @Bean
  public PaginationInterceptor paginationInterceptor() {
    PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
    paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
    return paginationInterceptor;
  }
 
  @Bean
  public PageHelper pageHelper() {
    PageHelper pageHelper = new PageHelper();
    Properties properties = new Properties();
    //offsetAsPageNum设置为true时,第一个参数offset当成pageNum页码使用
    properties.setProperty("offsetAsPageNum", "true");
    //设置为true时,使用RowBounds分页会进行count查询
    properties.setProperty("rowBoundsWithCount", "true");
    //启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页
    properties.setProperty("reasonable", "true");
    pageHelper.setProperties(properties);
    return pageHelper;
  }
}
 
4.创建对应得测试类

springboot集成pageHelper实现分页查询

 

 springboot集成pageHelper实现分页查询

5.测试

springboot集成pageHelper实现分页查询

 

 

 

上一篇:Java开发面试题,用了这么多年分页PageHelper


下一篇:PageHelper使用