分頁助手PageHelper的使用

分頁助手PageHelper的使用

簡介

pagehelper是一個很好用的mybatis的分頁插件,經過這個插件能夠很是方便的實現分頁功能。java

官網地址mysql

使用

這個插件的使用方式很是簡單。git

引入依賴

新建一個springboot項目,添加如下依賴:github

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>

<!--mapper-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.1.5</version>
</dependency>
<!--pagehelper 分頁-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.5</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

添加配置

#數據庫
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/study_springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root

#mybatis
mybatis.type-aliases-package=com.njit.model
mybatis.mapper-locations=classpath:mapper/*.xml

#pagehelper
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

而後在啓動類上指定tk-mapper的包名。web

@SpringBootApplication
@MapperScan("com.njit.mapper")
public class PagehelperDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(PagehelperDemoApplication.class, args);
    }

}

添加數據庫的實體類

@Data
public class User {

    private Integer id;

    private String name;

    private String password;
}

編寫通用mapper

import com.njit.model.User;
import tk.mybatis.mapper.common.Mapper;

/**
 * @Author: njitzyd
 * @Date: 2021/2/21 22:28
 * @Description: UserMapper
 * @Version 1.0.0
 */
public interface UserMapper  extends Mapper<User> {
}

測試

實際使用中只要在進行數據庫查詢的前面用靜態方法指定分頁的參數便可。spring

@SpringBootTest
class PagehelperDemoApplicationTests {

    @Autowired
    private UserMapper userMapper;
    @Test
    void contextLoads() {
        PageHelper.startPage(2,3);
        userMapper.selectAll().forEach(e->
                System.out.println(e)
        );
    }

}

會輸出以下結果:sql

image-20210221224510992

和咱們預期的數據符合,數據庫中的數據以下圖:數據庫

image-20210221224556217

總結

到此,分頁助手的基本使用就介紹完畢了。springboot

相關文章
相關標籤/搜索