SpringBoot使用Mybatis-PageHelper

前言

之前一篇文章介紹了《SpringBoot+Mybatis+MySql學習》的整合森枪,這一片擴展一下Mybatis的分頁插件-Mybatis-PageHelper。

新建項目

首先祷安,pom文件中加入pagehelper依賴,完整pom代碼如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dalaoyang</groupId>
    <artifactId>springboot_mybatis_pagehelper</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot_mybatis_pagehelper</name>
    <description>springboot_mybatis_pagehelper</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--pagehelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

配置文件增加PageHelper的配置,由于demo很簡單,只用到了分頁胶征,所以沒有增加其他配置,只設置了分頁方言桨仿,完整代碼如下:

##端口號
server.port=8888

##日志級別
logging.level.com.dalaoyang.dao.UserMapper=debug

##數(shù)據(jù)庫url
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
##數(shù)據(jù)庫用戶名
spring.datasource.username=root
##數(shù)據(jù)庫密碼
spring.datasource.password=root
##數(shù)據(jù)庫驅動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver



#pagehelper分頁插件配置
pagehelper.helperDialect=mysql

實體類User代碼如下:

package com.dalaoyang.entity;

import org.apache.ibatis.type.Alias;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.entity
 * @email 397600342@qq.com
 * @date 2018/6/22
 */
@Alias("user")
public class User {

    private int id;
    private String user_name;
    private String user_password;

    public User(String user_name, String user_password) {
        this.user_name = user_name;
        this.user_password = user_password;
    }

    public User(int id, String user_name, String user_password) {
        this.id = id;
        this.user_name = user_name;
        this.user_password = user_password;
    }

    public int getId() {
        return id;
    }

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

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getUser_password() {
        return user_password;
    }

    public void setUser_password(String user_password) {
        this.user_password = user_password;
    }
}

啟動類代碼如下:

package com.dalaoyang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootMybatisPagehelperApplication {

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

新建一個UserMapper睛低,之前介紹的整合mybatis是使用的mapper方式,本文選擇使用注解方式服傍,代碼如下:

package com.dalaoyang.dao;

import com.dalaoyang.entity.User;
import com.github.pagehelper.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;


/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.dao
 * @email 397600342@qq.com
 * @date 2018/6/22
 */
@Mapper
public interface UserMapper {

    @Select("SELECT * FROM USER")
    Page<User> getUserList();
}

還是一如既往的使用controller作為測試钱雷,代碼如下:

package com.dalaoyang.controller;

import com.dalaoyang.dao.UserMapper;
import com.dalaoyang.entity.User;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.controller
 * @email 397600342@qq.com
 * @date 2018/6/22
 */
@RestController
public class UserController {

    @Autowired
    UserMapper userMapper;

    //http://localhost:8888/getUserList?pageNum=1&pageSize=2
    @RequestMapping("/getUserList")
    public Page<User> getUserList(Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        Page<User>  userList= userMapper.getUserList();
        return userList;
    }
}

到這里項目就完全創(chuàng)建完成了。

測試

瀏覽器訪問http://localhost:8888/getUserList?pageNum=1&pageSize=2吹零,結果如下:

image

然后查看控制臺如下:

image

可以看到sql已經(jīng)進行分頁了罩抗。

然后回頭看controller的方法,返回的Page對象中包含了很多關于分頁的參數(shù)等數(shù)據(jù)瘪校,下面是Page的代碼,具體使用可以查看一下:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.github.pagehelper;

import java.io.Closeable;
import java.util.ArrayList;
import java.util.List;

public class Page<E> extends ArrayList<E> implements Closeable {
    private static final long serialVersionUID = 1L;
    private int pageNum;
    private int pageSize;
    private int startRow;
    private int endRow;
    private long total;
    private int pages;
    private boolean count;
    private Boolean reasonable;
    private Boolean pageSizeZero;
    private String countColumn;
    private String orderBy;
    private boolean orderByOnly;

    public Page() {
        this.count = true;
    }

    public Page(int pageNum, int pageSize) {
        this(pageNum, pageSize, true, (Boolean)null);
    }

    public Page(int pageNum, int pageSize, boolean count) {
        this(pageNum, pageSize, count, (Boolean)null);
    }

    private Page(int pageNum, int pageSize, boolean count, Boolean reasonable) {
        super(0);
        this.count = true;
        if (pageNum == 1 && pageSize == 2147483647) {
            this.pageSizeZero = true;
            pageSize = 0;
        }

        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.count = count;
        this.calculateStartAndEndRow();
        this.setReasonable(reasonable);
    }

    public Page(int[] rowBounds, boolean count) {
        super(0);
        this.count = true;
        if (rowBounds[0] == 0 && rowBounds[1] == 2147483647) {
            this.pageSizeZero = true;
            this.pageSize = 0;
        } else {
            this.pageSize = rowBounds[1];
            this.pageNum = rowBounds[1] != 0 ? (int)Math.ceil(((double)rowBounds[0] + (double)rowBounds[1]) / (double)rowBounds[1]) : 0;
        }

        this.startRow = rowBounds[0];
        this.count = count;
        this.endRow = this.startRow + rowBounds[1];
    }

    public List<E> getResult() {
        return this;
    }

    public int getPages() {
        return this.pages;
    }

    public Page<E> setPages(int pages) {
        this.pages = pages;
        return this;
    }

    public int getEndRow() {
        return this.endRow;
    }

    public Page<E> setEndRow(int endRow) {
        this.endRow = endRow;
        return this;
    }

    public int getPageNum() {
        return this.pageNum;
    }

    public Page<E> setPageNum(int pageNum) {
        this.pageNum = this.reasonable != null && this.reasonable && pageNum <= 0 ? 1 : pageNum;
        return this;
    }

    public int getPageSize() {
        return this.pageSize;
    }

    public Page<E> setPageSize(int pageSize) {
        this.pageSize = pageSize;
        return this;
    }

    public int getStartRow() {
        return this.startRow;
    }

    public Page<E> setStartRow(int startRow) {
        this.startRow = startRow;
        return this;
    }

    public long getTotal() {
        return this.total;
    }

    public void setTotal(long total) {
        this.total = total;
        if (total == -1L) {
            this.pages = 1;
        } else {
            if (this.pageSize > 0) {
                this.pages = (int)(total / (long)this.pageSize + (long)(total % (long)this.pageSize == 0L ? 0 : 1));
            } else {
                this.pages = 0;
            }

            if (this.reasonable != null && this.reasonable && this.pageNum > this.pages) {
                this.pageNum = this.pages;
                this.calculateStartAndEndRow();
            }

        }
    }

    public Boolean getReasonable() {
        return this.reasonable;
    }

    public Page<E> setReasonable(Boolean reasonable) {
        if (reasonable == null) {
            return this;
        } else {
            this.reasonable = reasonable;
            if (this.reasonable && this.pageNum <= 0) {
                this.pageNum = 1;
                this.calculateStartAndEndRow();
            }

            return this;
        }
    }

    public Boolean getPageSizeZero() {
        return this.pageSizeZero;
    }

    public Page<E> setPageSizeZero(Boolean pageSizeZero) {
        if (pageSizeZero != null) {
            this.pageSizeZero = pageSizeZero;
        }

        return this;
    }

    public String getOrderBy() {
        return this.orderBy;
    }

    public <E> Page<E> setOrderBy(String orderBy) {
        this.orderBy = orderBy;
        return this;
    }

    public boolean isOrderByOnly() {
        return this.orderByOnly;
    }

    public void setOrderByOnly(boolean orderByOnly) {
        this.orderByOnly = orderByOnly;
    }

    private void calculateStartAndEndRow() {
        this.startRow = this.pageNum > 0 ? (this.pageNum - 1) * this.pageSize : 0;
        this.endRow = this.startRow + this.pageSize * (this.pageNum > 0 ? 1 : 0);
    }

    public boolean isCount() {
        return this.count;
    }

    public Page<E> setCount(boolean count) {
        this.count = count;
        return this;
    }

    public Page<E> pageNum(int pageNum) {
        this.pageNum = this.reasonable != null && this.reasonable && pageNum <= 0 ? 1 : pageNum;
        return this;
    }

    public Page<E> pageSize(int pageSize) {
        this.pageSize = pageSize;
        this.calculateStartAndEndRow();
        return this;
    }

    public Page<E> count(Boolean count) {
        this.count = count;
        return this;
    }

    public Page<E> reasonable(Boolean reasonable) {
        this.setReasonable(reasonable);
        return this;
    }

    public Page<E> pageSizeZero(Boolean pageSizeZero) {
        this.setPageSizeZero(pageSizeZero);
        return this;
    }

    public Page<E> countColumn(String columnName) {
        this.countColumn = columnName;
        return this;
    }

    public PageInfo<E> toPageInfo() {
        PageInfo<E> pageInfo = new PageInfo(this);
        return pageInfo;
    }

    public PageSerializable<E> toPageSerializable() {
        PageSerializable<E> serializable = new PageSerializable(this);
        return serializable;
    }

    public <E> Page<E> doSelectPage(ISelect select) {
        select.doSelect();
        return this;
    }

    public <E> PageInfo<E> doSelectPageInfo(ISelect select) {
        select.doSelect();
        return this.toPageInfo();
    }

    public <E> PageSerializable<E> doSelectPageSerializable(ISelect select) {
        select.doSelect();
        return this.toPageSerializable();
    }

    public long doCount(ISelect select) {
        this.pageSizeZero = true;
        this.pageSize = 0;
        select.doSelect();
        return this.total;
    }

    public String getCountColumn() {
        return this.countColumn;
    }

    public void setCountColumn(String countColumn) {
        this.countColumn = countColumn;
    }

    public String toString() {
        return "Page{count=" + this.count + ", pageNum=" + this.pageNum + ", pageSize=" + this.pageSize + ", startRow=" + this.startRow + ", endRow=" + this.endRow + ", total=" + this.total + ", pages=" + this.pages + ", reasonable=" + this.reasonable + ", pageSizeZero=" + this.pageSizeZero + '}' + super.toString();
    }

    public void close() {
        PageHelper.clearPage();
    }
}

其他

關于更多Mybatis-PageHelper配置及介紹可以查看下面網(wǎng)站:
https://gitee.com/free/Mybatis_PageHelper
https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

源碼下載 :大老楊碼云

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末名段,一起剝皮案震驚了整個濱河市阱扬,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌伸辟,老刑警劉巖麻惶,帶你破解...
    沈念sama閱讀 211,743評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異信夫,居然都是意外死亡窃蹋,警方通過查閱死者的電腦和手機卡啰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,296評論 3 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來警没,“玉大人匈辱,你說我怎么就攤上這事∩奔#” “怎么了亡脸?”我有些...
    開封第一講書人閱讀 157,285評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長树酪。 經(jīng)常有香客問我浅碾,道長,這世上最難降的妖魔是什么续语? 我笑而不...
    開封第一講書人閱讀 56,485評論 1 283
  • 正文 為了忘掉前任垂谢,我火速辦了婚禮,結果婚禮上疮茄,老公的妹妹穿的比我還像新娘滥朱。我一直安慰自己,他們只是感情好娃豹,可當我...
    茶點故事閱讀 65,581評論 6 386
  • 文/花漫 我一把揭開白布焚虱。 她就那樣靜靜地躺著,像睡著了一般懂版。 火紅的嫁衣襯著肌膚如雪鹃栽。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,821評論 1 290
  • 那天躯畴,我揣著相機與錄音民鼓,去河邊找鬼。 笑死蓬抄,一個胖子當著我的面吹牛丰嘉,可吹牛的內容都是我干的。 我是一名探鬼主播嚷缭,決...
    沈念sama閱讀 38,960評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼饮亏,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了阅爽?” 一聲冷哼從身側響起路幸,我...
    開封第一講書人閱讀 37,719評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎付翁,沒想到半個月后简肴,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,186評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡百侧,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,516評論 2 327
  • 正文 我和宋清朗相戀三年砰识,在試婚紗的時候發(fā)現(xiàn)自己被綠了能扒。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,650評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡辫狼,死狀恐怖初斑,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情予借,我是刑警寧澤越平,帶...
    沈念sama閱讀 34,329評論 4 330
  • 正文 年R本政府宣布,位于F島的核電站灵迫,受9級特大地震影響秦叛,放射性物質發(fā)生泄漏。R本人自食惡果不足惜瀑粥,卻給世界環(huán)境...
    茶點故事閱讀 39,936評論 3 313
  • 文/蒙蒙 一挣跋、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧狞换,春花似錦避咆、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,757評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至黄琼,卻和暖如春樊销,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背脏款。 一陣腳步聲響...
    開封第一講書人閱讀 31,991評論 1 266
  • 我被黑心中介騙來泰國打工围苫, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人撤师。 一個月前我還...
    沈念sama閱讀 46,370評論 2 360
  • 正文 我出身青樓剂府,卻偏偏與公主長得像,于是被迫代替她去往敵國和親剃盾。 傳聞我的和親對象是個殘疾皇子腺占,可洞房花燭夜當晚...
    茶點故事閱讀 43,527評論 2 349

推薦閱讀更多精彩內容

  • Mybatis分頁插件-PageHepler的使用 使用方法 1. 引入分頁插件 引入分頁插件一共有下面2種方式,...
    匆匆歲月閱讀 1,418評論 0 7
  • 早上5.40起來了痒谴,只是做了一組拉伸及簡單的行走運動衰伯,就倒下了。跟女友睡到11點才醒闰歪,今天跟好朋友聯(lián)系了聚會的事嚎研,...
    阿麥_bdb1閱讀 142評論 0 0
  • 把成交變得簡單临扮、純粹,這樣的人也會變的簡單教翩、純粹 你簡單了純粹了杆勇,你的世界就簡單了純粹了
    農(nóng)爸爸閱讀 129評論 0 0