Java教程

springboot集成pageHelper实现分页查询

本文主要是介绍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.创建对应得测试类

 

 

5.测试

 

 

 

这篇关于springboot集成pageHelper实现分页查询的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!