search
HomeJavajavaTutorialHow to use PageHelper in springboot+mybatis framework

How to use PageHelper in springboot+mybatis framework

May 12, 2023 pm 03:55 PM
mybatisspringbootpagehelper

1. Idea

Put all the content required for paging into an entity class

The entity class required for paging data! It contains page number, page size, total number of entries, total number of pages, starting line

pagehelpr provides this class pageInfo, we don’t need to create it ourselves

2. Main logic

select * from table name limit starting row, display several pieces of data

#Page n displays five pieces of data per page

select * from table name limit ( n-1)*5,5

#How many items are displayed on each page pageSize

3

#How many items are there in total

total

select count (*) from table name

#Total number of pages

pages

pages=total%pagesSize==0?total/pgeSize:total/pageSize 1 ;

#Current page

pageNum

3. Steps

1.Introduce pagehelper dependency

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.5</version>
</dependency>
#pagehelper分页插件配置
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql

2.bean Entity class

User entity:

package com.qianfeng.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
 
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Register {
    private Integer id;
 
    private String userName;
 
    private String passWord;
 
    private String rePassWord;
 
    private String idCard;
    private String gender;
 
}

Returns the front-end entity class: including the found data and paging data

package com.qianfeng.bean;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
 
import java.util.List;
 
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class RegPage {
    private PageInfo pageInfo;
    private List<Register> registers;
}

2.mapper layer:

package com.qianfeng.mapper;
 
import com.qianfeng.bean.Register;
import org.apache.ibatis.annotations.Mapper;
 
import java.util.List;
@Mapper
public interface PageDao {
    List<Register> getAll(Integer startRow,Integer pageSize);
    long getCount();
}

3.service layer:

package com.qianfeng.service;
 
import com.github.pagehelper.PageInfo;
import com.qianfeng.bean.RegPage;
 
public interface RegService {
    RegPage getAll(PageInfo pageInfo);
}

4.serviceImpl:

package com.qianfeng.service.serviceImpl;
 
import com.github.pagehelper.PageInfo;
import com.qianfeng.bean.RegPage;
import com.qianfeng.bean.Register;
import com.qianfeng.mapper.PageDao;
import com.qianfeng.service.RegService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.List;
 
@Service
public class RegServiceImpl implements RegService {
    @Autowired
    private PageDao pageDao;
    @Override
    public RegPage getAll(PageInfo pageInfo) {
        List<Register> all = pageDao.getAll(pageInfo.getStartRow(), pageInfo.getPageSize());//分页后的数据
        long count = pageDao.getCount();//总记录条数
        pageInfo.setTotal(count);
        //总页数
        int pages= (int) (pageInfo.getTotal()%pageInfo.getPageSize()==0?pageInfo.getTotal()/pageInfo.getPageSize():pageInfo.getTotal()/pageInfo.getPageSize()+1);
        pageInfo.setPages(pages);
 
        RegPage regPage = new RegPage();
        regPage.setPageInfo(pageInfo);
        regPage.setRegisters(all);
        return regPage;
 
    }
}

5.handler layer:

package com.qianfeng.handler;
 
import com.github.pagehelper.PageInfo;
import com.qianfeng.bean.RegPage;
import com.qianfeng.service.RegService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class RegHandler {
    @Autowired
    private RegService regService;
    @RequestMapping("/page/{pageNum}")
    public RegPage regPage(@PathVariable("pageNum") Integer pageNum){
        System.out.println(".........");
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(3);
        pageInfo.setStartRow((pageNum-1)*pageInfo.getPageSize());
        System.out.println("startRow" + pageInfo.getStartRow());
        return regService.getAll(pageInfo);
    }
}

6.mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qianfeng.mapper.PageDao">
    <select id="getAll" resultType="com.qianfeng.bean.Register">
        select * from m_register limit #{startRow},#{pageSize}
    </select>
    <select id="getCount" resultType="java.lang.Long">
        select count(*) from m_register
    </select>
</mapper>

7. application.yaml

spring:
  datasource:
    url: jdbc:mysql:///map?serverTimezone=Asia/Shanghai&useSSL=false
    username: root
    password: 123
    driver-class-name: com.mysql.jdbc.Driver
 
    druid:
      aop-patterns: com.qianfeng.*  #监控SpringBean
      filters: stat,wall     # 底层开启功能,stat(sql监控),wall(防火墙)
 
      stat-view-servlet:   # 配置监控页功能
        enabled: true
        login-username: admin
        login-password: admin
        resetEnable: false
 
      web-stat-filter:  # 监控web
        enabled: true
        urlPattern: /*
        exclusions: &#39;*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*&#39;
      filter:
        stat:    # 对上面filters里面的stat的详细配置
          slow-sql-millis: 1000
          logSlowSql: true
          enabled: true
        wall:
          enabled: true
          config:
            drop-table-allow: false
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
# mybatis的配置规则
mybatis:
  #config-location: classpath:mapper/mybatis-config.xml
  mapper-locations: classpath:mapper/*
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#      static-locations: [classpath:/haha/]  # 静态资源路径自定义

8.application,properties

spring.main.allow-circular-references=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql

About the PageInfo class, the source code is as follows:

public class PageInfo implements Serializable {
private static final long serialVersionUID = 1L;
//当前页
private int pageNum;
//每页的数量
private int pageSize;
//当前页的数量
private int size;
//由于startRow 和endRow 不常用,这里说个具体的用法
//可以在页面中"显示startRow 到endRow 共size 条数据"
//当前页面第一个元素在数据库中的行号
private int startRow;
//当前页面最后一个元素在数据库中的行号
private int endRow;
//总记录数
private long total;
//总页数
private int pages;
//结果集
private List list;
//前一页
private int prePage;
//下一页
private int nextPage;
//是否为第一页
private boolean isFirstPage = false;
//是否为最后一页
private boolean isLastPage = false;
//是否有前一页
private boolean hasPreviousPage = false;
//是否有下一页
private boolean hasNextPage = false;
//导航页码数
private int navigatePages;
//所有导航页号
private int[] navigatepageNums;
//导航条上的第一页
private int navigateFirstPage;
//导航条上的最后一页
private int navigateLastPage;
}

Directory structure:

How to use PageHelper in springboot+mybatis framework

The above is the detailed content of How to use PageHelper in springboot+mybatis framework. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does the JVM handle differences in operating system APIs?How does the JVM handle differences in operating system APIs?Apr 27, 2025 am 12:18 AM

JVM handles operating system API differences through JavaNativeInterface (JNI) and Java standard library: 1. JNI allows Java code to call local code and directly interact with the operating system API. 2. The Java standard library provides a unified API, which is internally mapped to different operating system APIs to ensure that the code runs across platforms.

How does the modularity introduced in Java 9 impact platform independence?How does the modularity introduced in Java 9 impact platform independence?Apr 27, 2025 am 12:15 AM

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

What is bytecode, and how does it relate to Java's platform independence?What is bytecode, and how does it relate to Java's platform independence?Apr 27, 2025 am 12:06 AM

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf

Why is Java considered a platform-independent language?Why is Java considered a platform-independent language?Apr 27, 2025 am 12:03 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),whichexecutesbytecodeonanydevicewithaJVM.1)Javacodeiscompiledintobytecode.2)TheJVMinterpretsandexecutesthisbytecodeintomachine-specificinstructions,allowingthesamecodetorunondifferentp

How can graphical user interfaces (GUIs) present challenges for platform independence in Java?How can graphical user interfaces (GUIs) present challenges for platform independence in Java?Apr 27, 2025 am 12:02 AM

Platform independence in JavaGUI development faces challenges, but can be dealt with by using Swing, JavaFX, unifying appearance, performance optimization, third-party libraries and cross-platform testing. JavaGUI development relies on AWT and Swing, which aims to provide cross-platform consistency, but the actual effect varies from operating system to operating system. Solutions include: 1) using Swing and JavaFX as GUI toolkits; 2) Unify the appearance through UIManager.setLookAndFeel(); 3) Optimize performance to suit different platforms; 4) using third-party libraries such as ApachePivot or SWT; 5) conduct cross-platform testing to ensure consistency.

What aspects of Java development are platform-dependent?What aspects of Java development are platform-dependent?Apr 26, 2025 am 12:19 AM

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Are there performance differences when running Java code on different platforms? Why?Are there performance differences when running Java code on different platforms? Why?Apr 26, 2025 am 12:15 AM

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

What are some limitations of Java's platform independence?What are some limitations of Java's platform independence?Apr 26, 2025 am 12:10 AM

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function