SpringBoot 整合Mybatis + PageHelper 實現分頁


前言:

  • 現在公司大多數都實現了前后端分離,前端使用Vue、React、AngularJS 等框架,不用完全依賴后端。但是如果對於比較小型的項目,沒必要前后端分離,而SpringBoot也基本拋棄了Jsp,使用Thymeleaf模板搭配SpringBoot是個不錯的選擇。
  • 在展示數據時必然需要大量的分頁操作,在使用JPA、Mybatis-Plus等持久層框架時,已經自帶分頁查詢操作,無需手動編寫,然而在使用Mybatis作為持久層時,需要手動編寫分頁操作十分麻煩。PageHelper就是用來在Mybatis之上幫助我們實現分頁操作。

開發環境:

  • IDEA IntelliJ IDEA 2019.3.3 x64
  • JDK: 1.8
  • SpringBoot: 2.25
  • PageHelper: 1.2.13
  • Mybatis: 2.1.3 (使用Mybatis作為持久層)
  • 數據源:Druid 1.1.23

一、SpringBoot框架搭建

【1】點擊:File ---> New ---> Project

image-20200722002449351

【2】這個頁面選項是選擇SpringBoot需要的啟動依賴,在這里可以有很多選項,這里選擇 Web 和 SQL中的相應配置,然后點擊下一步。(這里的SpringBoot版本有些過高,可以選擇使用默認的最新版本)

image-20200722002852164

【3】保存路徑,點擊FINSH完成。

image-20200722003036710

二、詳細配置

1、在pom文件中引入Pagehelper分頁插件,Driud數據源(非必需)

<!-- Mybatis 分頁插件 -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.13</version>
</dependency>

<!-- Druid 數據源-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.23</version>
</dependency>

2、創建數據庫

數據庫名:pagehelperdemo 編碼字符集:utf8

CREATE DATABASE `pagehelperdemo`;

USE `pagehelperdemo`;

DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id主鍵',
  `username` varchar(20) NOT NULL COMMENT '用戶名',
  `PASSWORD` varchar(20) NOT NULL COMMENT '用戶密碼',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

insert  into `users`(`id`,`username`,`PASSWORD`) values 
(1,'onetest','123'),
(2,'twotest','456'),
(3,'onetest','789'),
(4,'twotest','987'),
(5,'onetest','654'),
(6,'twotest','321'),
(7,'onetest','147'),
(8,'twotest','258'),
(9,'onetest','369'),
(10,'twotest','963');

插入多條數據方便分頁查看。

image-20200722005028707

3、配置分頁插件

將resource文件夾下的application.properties配置文件改成yml后綴,即application.yml,進行如下配置

server:
  port: 8089

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/pagehelperdemo?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root

  thymeleaf:
    encoding: UTF-8
    prefix: classpath:/templates/
    suffix: .html
    cache: false
    
#mybatis:
#  mapper-locations: classpath:/mapper/*.xml  #項目中使用注解進行開發

pagehelper:
  helper-dialect: mysql # 指定數據庫類型
  reasonable: true
  params: count=countSql
  support-methods-arguments: true

三、代碼編寫

1、創建用戶實體類

package com.jia.pojo;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ButterflyStars
 * @DateTime: Created in 2020/7/22 1:28
 * @QQ: 1498575492
 * Description: 用戶信息實體類
 */
public class User {
    private Integer id;
    private String username;
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

2、創建用戶持久層接口:UserDaoMapper

package com.jia.mapper;

import com.jia.pojo.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ButterflyStars
 * @DateTime: Created in 2020/7/22 1:31
 * @QQ: 1498575492
 * Description: 用戶持久層接口
 */
public interface UserDaoMapper {
    //查詢所有用戶
    @Select("select id,username,password from users")
    List<User> getAllUser();
}

3、創建業務層接口和實現類:UserService、UserServiceImpl

package com.jia.service;

import com.jia.pojo.User;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ButterflyStars
 * @DateTime: Created in 2020/7/22 1:35
 * @QQ: 1498575492
 * Description: 用戶業務層接口
 */
public interface UserService {
    //查詢所有用戶
    List<User> getAllUser();
}
package com.jia.service.impl;

import com.jia.mapper.UserDaoMapper;
import com.jia.pojo.User;
import com.jia.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ButterflyStars
 * @DateTime: Created in 2020/7/22 1:36
 * @QQ: 1498575492
 * Description: 用戶業務層接口實現類
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserDaoMapper userDaoMapper;

    @Override
    public List<User> getAllUser() {
        return userDaoMapper.getAllUser();
    }
}

4、創建用戶控制層:UserController

【1】 編寫測試Cntroller,檢測是否能查詢到數據。

package com.jia.controller;

import com.jia.pojo.User;
import com.jia.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ButterflyStars
 * @DateTime: Created in 2020/7/22 1:39
 * @QQ: 1498575492
 * Description: 用戶控制層
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/findAll")
    @ResponseBody
    public List<User> findUser() {
        List<User> userList = userService.getAllUser();
        return userList;
    }
}

【2】數據查詢成功。

image-20200722105524501

【3】修改后的UserController

package com.jia.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jia.pojo.User;
import com.jia.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ButterflyStars
 * @DateTime: Created in 2020/7/22 1:39
 * @QQ: 1498575492
 * Description: 用戶控制層
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * @param model
     * @param pageNum  當前頁數
     * @return
     */
    @GetMapping("/findAll")
    public String findUser(Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum) {
        PageHelper.startPage(pageNum,5);    // 默認從第一頁開始,每頁展示五條數據
        List<User> userList = userService.getAllUser();
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        model.addAttribute("pageInfo",pageInfo);
        return "index";
    }
}

5、添加 MapperScan 注解

修改 啟動文件,在類前添加 MapperScan 注解,修改后如下:

package com.jia;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

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

}

6、創建index.html頁面,引入Thymeleaf依賴

注意:對user進行取值時,屬性會有紅色波浪線提示,並不影響運行。

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>分頁測試</title>
</head>
<body>
<h3>查詢所有用戶</h3>
<table border="1">
    <tr>
        <th>id</th>
        <th>name</th>
        <th>password</th>
    </tr>
    <tr th:each="user:${pageInfo.list}">
        <td th:text="${user.id}"></td>
        <td th:text="${user.username}"></td>
        <td th:text="${user.password}"></td>
    </tr>
</table>
<p>當前 <span th:text="${pageInfo.pageNum}"></span> 頁,總 <span th:text="${pageInfo.pages}"></span> 頁,共 <span th:text="${pageInfo.total}"></span> 條記錄</p>
<a th:href="@{/user/findAll}">首頁</a>
<a th:href="@{/user/findAll(pageNum=${pageInfo.hasPreviousPage}?${pageInfo.prePage}:1)}">上一頁</a>
<a th:href="@{/user/findAll(pageNum=${pageInfo.hasNextPage}?${pageInfo.nextPage}:${pageInfo.pages})}">下一頁</a>
<a th:href="@{/user/findAll(pageNum=${pageInfo.pages})}">尾頁</a>
</body>
</html>

四、運行測試

啟動 SpringBoot 工程,在瀏覽器輸入:http://localhost:8089/user/findAll,可以看到網頁顯示用戶信息表格,點擊上一頁、下一頁可以進行頁面切換顯示數據。

image-20200722113000115


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM