springboot 中 分頁實現
本次要講的是典型的兩種分頁方式,即sql分頁和外掛分頁。
依賴
因為使用了mybatis、mysql ,所以要新增相關依賴。這裡版本沒有特別需求,選擇你想要的版本即可。
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId >
<version>${mybatis-version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-version}</version >
</dependency>
本人使用的版本:
<mybatis-version>1.3.1</mybatis-version>
<mysql-version>5.1.32</mysql-version>
sql分頁
基於sql語句
的分頁,不需要特殊依賴。
Dao層
在ArticleMapper .java
中,分頁函式如下:
package com.sqlb.mapper;
import com.sqlb.pojo.Article;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
@Mapper
public interface ArticleMapper {
/**
*sql 分頁
*/
List<Article> list(Map<String, Object> map);
}
對應的ArticleMapper .xml
中如下:
<select id="list" resultType="com.sqlb.pojo.Article">
select
<include refid="Base_Column_List"/>
from article
<where>
<if test="id != null and id != ''">and id = #{id}</if>
<if test="author != null and author != ''">and author = #{author}</if>
<if test="createTime != null and createTime != ''">and create_time = #{createTime}</if>
<if test="typeName != null and typeName != ''">and type_name = #{typeName}</if>
<if test="imageUrl != null and imageUrl != ''">and image_url = #{imageUrl}</if>
<if test="content != null and content != ''">and content = #{content}</if>
</where>
<choose>
<when test="createTime != null and createTime.trim() != ''">
order by ${createTime}
</when>
<otherwise>
order by id desc
</otherwise>
</choose>
<if test="offset != null and limit != null">
limit #{offset}, #{limit}
</if>
</select>
Service層
@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleMapper articleMapper;
@Override
public List<Article> list(Integer pageNum, Integer pageSize) {
return articleMapper.listWithBLOBs(PageParam.getParams(pageNum, pageSize));
}
}
Controller層
@Controller
@RequestMapping("/article")
public class ArticleController {
@Autowired
ArticleService articleService;
@ResponseBody
@RequestMapping("/list")
public List<Article> list(@RequestParam(defaultValue = "1",value = "currentPage") Integer pageNum,
@RequestParam(defaultValue = "10",value = "pageSize") Integer pageSize){
return articleService.list(pageNum,pageSize);
}
}
當然,使用mybatis
記得在application.yml
中配置一把,以及mysql
資料連線池配置。
mybatis:
configuration:
map-underscore-to-camel-case: true
mapper-locations: mybatis/*/*Mapper.xml
type-aliases-package: com.sqlb.pojo
mysql
資料連線池配置這裡就不用多說了吧。不知道的,就趕緊去學習下基礎知識。
Article類和表結構
- Article類
import java.util.Date;
public class Article {
private Integer id;
private String author;
private Date createTime;
private String typeName;
private String imageUrl;
private String content;
//此處省去get、set方法
}
表結構
CREATE TABLE `article` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id編號', `content` text NOT NULL COMMENT '文章內容,程式碼控制不可超過1000字', `author` varchar(128) DEFAULT NULL COMMENT '作者', `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '建立時間', `type_name` enum('0','1','2','3','4') NOT NULL DEFAULT '1' COMMENT '文章型別', `image_url` varchar(255) DEFAULT NULL COMMENT '圖片地址', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8mb4;
sql分頁
就是這麼多了,執行訪問http://localhost:8081/article/list
可以得到你想要的資料。
外掛分頁
顯然,這種方法是要匯入第三方jar包的,具體方法如下。
外掛依賴
<!--分頁外掛-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper-version}</version>
</dependency>
這裡要說明一下,本人使用的版本是:
<pagehelper-version>1.1.1</pagehelper-version>
本人開始使用的是當前最新版本1.2.4
,本人這裡不行,內部原因不詳。您如果使用拋錯的話,建議可以切換不同版本試試。
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.4</version>
</dependency>
配置
springboot
最大的特色就是隻需簡單的配置,就可以進行快捷的開發,配置如下:
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countSql
Dao層
ArticleMapper .java
import com.github.pagehelper.Page;
import com.sqlb.pojo.Article;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
@Mapper
public interface ArticleMapper {
/**
* 外掛 分頁 查詢表中部分欄位
*/
Page<Article> findByPage();
/**
* 外掛 分頁 查詢表中所有欄位
*/
Page<Article> findWithBLOBsByPage();
}
ArticleMapper .xml
<select id="findByPage" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from article
</select>
<select id="findWithBLOBsByPage" resultMap="ResultMapWithBLOBs">
select
<include refid="Base_Column_List"/>
,
<include refid="Blob_Column_List"/>
from article
</select>
這裡有兩個分頁,不同點就是findWithBLOBsByPage
把所有的欄位都查詢出來了,而findByPage
相比之下少查詢了一個欄位。這裡需要提出的是,本人的使用findByPage
查詢部分欄位時,會報java.lang.NoSuchMethodException
錯誤,具體原因暫時不詳,以後明白了再記出來,如果哪個大神明白細節的還望不吝賜教~~~
Service層
此處才用到PageHelper外掛
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sqlb.mapper.ArticleMapper;
import com.sqlb.pojo.Article;
import com.sqlb.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleMapper articleMapper;
@Override
public Page<Article> findByPage(Integer pageNum, Integer pageSize) {
//用外掛進行分頁
PageHelper.startPage(pageNum, pageSize);
return articleMapper.findByPage();
}
@Override
public Page<Article> findWithBLOBsByPage(Integer pageNum, Integer pageSize) {
//用外掛進行分頁
PageHelper.startPage(pageNum, pageSize);
return articleMapper.findWithBLOBsByPage();
}
}
Controller層
首先要建立一個返回給前端的pojo物件
,新建一個分頁資料類PageInfo
:
import com.github.pagehelper.Page;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
/**
* @描敘: 分頁 資料結構
*/
public class PageInfo<T> implements Serializable {
private static final long serialVersionUID = 1L;
//當前頁
private int pageNum;
//每頁的數量
private int pageSize;
//總記錄數
private long total;
//總頁數
private int pages;
//結果集
private List<T> list;
//是否為第一頁
private boolean isFirstPage = false;
//是否為最後一頁
private boolean isLastPage = false;
public PageInfo() {
}
/**
* 包裝Page物件
*
* @param list
*/
public PageInfo(List<T> list) {
if (list instanceof Page) {
Page page = (Page) list;
this.pageNum = page.getPageNum();
this.pageSize = page.getPageSize();
this.pages = page.getPages();
this.list = page;
this.total = page.getTotal();
} else if (list instanceof Collection) {
this.pageNum = 1;
this.pageSize = list.size();
this.pages = 1;
this.list = list;
this.total = list.size();
}
if (list instanceof Collection) {
//判斷頁面邊界
judgePageBoudary();
}
}
/**
* 判定頁面邊界
*/
private void judgePageBoudary() {
isFirstPage = pageNum == 1;
isLastPage = pageNum == pages;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public boolean isIsFirstPage() {
return isFirstPage;
}
public void setIsFirstPage(boolean isFirstPage) {
this.isFirstPage = isFirstPage;
}
public boolean isIsLastPage() {
return isLastPage;
}
public void setIsLastPage(boolean isLastPage) {
this.isLastPage = isLastPage;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("PageInfo{");
sb.append("pageNum=").append(pageNum);
sb.append(", pageSize=").append(pageSize);
sb.append(", total=").append(total);
sb.append(", pages=").append(pages);
sb.append(", list=").append(list);
sb.append(", isFirstPage=").append(isFirstPage);
sb.append(", isLastPage=").append(isLastPage);
sb.append(", navigatepageNums=");
sb.append('}');
return sb.toString();
}
}
ArticleController.java
中,資料轉換如下:
import com.github.pagehelper.Page;
import com.sqlb.pojo.Article;
import com.sqlb.pojo.PageInfo; //剛才新建的分頁資料物件
import com.sqlb.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/article")
public class ArticleController {
@Autowired
ArticleService articleService;
@ResponseBody
@RequestMapping("/page")
public PageInfo<Article> findWithBLOBsByPage(@RequestParam(defaultValue = "1",value = "currentPage") Integer pageNum,
@RequestParam(defaultValue = "10",value = "pageSize") Integer pageSize){
Page<Article> articles = articleService.findWithBLOBsByPage(pageNum, pageSize);
// 需要把Page包裝成PageInfo物件才能序列化。該外掛也預設實現了一個PageInfo
PageInfo<Article> pageInfo = new PageInfo<>(articles);
return pageInfo;
}
}
外掛分頁
就是這麼多了,執行訪問http://localhost:8081/article/list
可以得到你想要的資料。