1. 程式人生 > 其它 >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.測試