Spring Boot 2.X 集成 Mybatis PageHelper 分頁插件解決一對多分頁查詢問題

1 摘要

每個項目中都會用到分頁查詢,這一技術具有高度的複用性,爲了避免每次創建新項目時重新編寫一邊分頁查詢,或者因爲項目的數據庫更換而重新編寫分頁代碼,將分頁查詢提取出來封裝成專門的第三方庫就顯得十分必要。本文將介紹基於 Spring Boot 2.X 集成 Mybatis PageHelper 分頁插件。

2 官方文檔

MyBatis Pagination - PageHelper

3 核心依賴

./pom.xml
./demo-dao/pom.xml
            <!-- mybatis pageHelper -->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>${mybatis.pagehelper.version}</version>
            </dependency>

其中 ${mybatis.pagehelper.version} 的版本爲 1.2.12

4 核心代碼

4.1 方法應用

./demo-service/src/main/java/com/ljq/demo/springboot/service/impl/ArticleServiceImpl.java
package com.ljq.demo.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ljq.demo.springboot.common.api.ApiResult;
import com.ljq.demo.springboot.common.page.QueryUtil;
import com.ljq.demo.springboot.dao.article.ArticleDao;
import com.ljq.demo.springboot.entity.ArticleEntity;
import com.ljq.demo.springboot.service.ArticleService;
import com.ljq.demo.springboot.vo.article.ArticleListParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 文章表業務層具體實現類
 *
 * @author junqiang.lu
 * @date 2019-11-25 14:01:38
 */
@Service("articleService")
@Transactional(rollbackFor = {Exception.class})
@Slf4j
public class ArticleServiceImpl implements ArticleService {

	@Autowired
	private ArticleDao articleDao;

	/**
	 * 查詢列表
	 *
	 * @param articleListParam
	 * @return
	 * @throws Exception
	 */
	@Override
	public ApiResult list(ArticleListParam articleListParam) throws Exception {
		long start = System.currentTimeMillis();
		QueryUtil queryMap = new QueryUtil(BeanUtil.beanToMap(articleListParam, false, true));
		PageInfo<ArticleEntity> pageInfo = PageHelper.startPage(articleListParam.getCurrPage(), articleListParam.getPageLimit())
				.setOrderBy(articleListParam.getProperties() + " " + articleListParam.getDirection())
				.doSelectPageInfo(() -> articleDao.queryListPage(queryMap));
		long end = System.currentTimeMillis();
		log.info("查詢耗時: {}", (end - start));
		return ApiResult.success(pageInfo);
	}

	
}

關於 PageHelper 的一些方法說明:

startPage: 設置查詢起始點與每頁顯示條數

setOrderBy: 設置排序規則

doSelectPageInfo: 需要執行的查詢語句,Mybatis Mapper 中定義的接口(支持 lambda 表達式),返回的結果是分頁信息PageInfo(包含結果列表以及分頁參數)

doSelectPage: 也是執行查詢語句,與 doSelectPageInfo 一樣,只是返回結果不同,doSelectPage 返回的是 Page, 如果將這個結果返回至前端,則只有數據列表,而沒有分頁信息。Page 可轉化爲 PageInfo

注意 : 方法順序必須是 startPage -> setOrderBy -> doSelectPage ,若將 setOrderBy 放在 doSelectPage 後邊,則排序不生效(親測結果是這樣的)

4.2 Mapper 文件

../demo-dao/src/main/resources/mapper/ArticleDao.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.ljq.demo.springboot.dao.article.ArticleDao">

	<!-- 文章表結果集resultMap -->
    <resultMap type="com.ljq.demo.springboot.entity.ArticleEntity" id="articleMap">
        <result property="id" column="id"/>
        <result property="title" column="title"/>
        <result property="content" column="content"/>
		<collection property="tagList" column="id" javaType="java.util.List" ofType="com.ljq.demo.springboot.entity.ArticleTagEntity"
					select="com.ljq.demo.springboot.dao.article.ArticleTagDao.queryTagsByArticleId">
			<id property="id" column="id" />
			<result property="tagName" column="tag_name" />
		</collection>
    </resultMap>

   <!-- 文章表-基礎字段 -->
	<sql id="article_base_field">
        a.`id`,
        a.`title`,
        a.`content`
	</sql>

	<!-- 文章表-列表字段 -->
	<sql id="article_list_field">
        <include refid="article_base_field" />
        ,
        at.`id` at_id,
        at.`tag_name` at_tag_name
	</sql>

	<!-- 列表查詢 -->
	<select id="queryListPage" parameterType="java.util.Map" resultMap="articleMap">
		SELECT
		<include refid="article_base_field" />
		FROM article a
		LEFT JOIN `article_to_tag` att ON att.article_id = a.id
		LEFT JOIN `article_tag` at ON at.id = att.tag_id
		WHERE 1 = 1
		<if test="title != null and '' != title">
			AND a.title LIKE CONCAT(CONCAT("%", #{title}), "%")
		</if>
		<if test="articleTag != null and '' != articleTag">
			AND at.tag_name LIKE CONCAT(CONCAT("%", #{articleTag}), "%")
		</if>
		GROUP BY a.id
	</select>



</mapper>
../demo-dao/src/main/resources/mapper/ArticleTagDao.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.ljq.demo.springboot.dao.article.ArticleTagDao">

	<!-- 文章標籤表結果集resultMap -->
    <resultMap type="com.ljq.demo.springboot.entity.ArticleTagEntity" id="articleTagMap">
        <result property="id" column="id"/>
        <result property="tagName" column="tag_name"/>
    </resultMap>

   <!-- 文章標籤表-基礎字段 -->
	<sql id="article_tag_base_field">
        at.`id`,
        at.`tag_name`
	</sql>

	<!-- 查詢某一篇文章的標籤(列表) S -->
	<select id="queryTagsByArticleId" parameterType="long" resultMap="articleTagMap">
		SELECT
		    <include refid="article_tag_base_field" />
		FROM `article_to_tag` att
		LEFT JOIN `article_tag` at ON at.id = att.tag_id
		LEFT JOIN `article` a ON a.id = att.article_id
		WHERE a.id = #{id}
	</select>
	<!-- 查詢某一篇文章的標籤(列表) E -->

</mapper>

注意: 在一對多的關係中,可以使用 collection 來對查詢結果進行封裝。在 collection 標籤中有 select 屬性,用於將一個子查詢結果封裝到 resultMap 中,這個查詢可以爲本 Mapper 文件中的查詢,也可以是其他 Mapper 文件的查詢,如果爲其他 Mapper 中的查詢,則需要指定具體的 Mapper ,具體參考示例中ArticleDao.xml的代碼

4.3 DAO 接口

../demo-dao/src/main/java/com/ljq/demo/springboot/dao/article/ArticleTagDao.java
package com.ljq.demo.springboot.dao.article;

import com.ljq.demo.springboot.dao.BaseDao;
import com.ljq.demo.springboot.entity.ArticleTagEntity;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 文章標籤表
 * 
 * @author junqiang.lu
 * @date 2019-11-25 14:01:38
 */
@Repository
public interface ArticleTagDao extends BaseDao<ArticleTagEntity> {

    /**
     * 查詢某一篇文章的標籤(列表)
     *
     * @param articleId
     * @return
     */
    List<ArticleTagEntity> queryTagsByArticleId(@Param("articleId") long articleId);

}
../demo-dao/src/main/java/com/ljq/demo/springboot/dao/article/ArticleDao.java
package com.ljq.demo.springboot.dao.article;

import com.ljq.demo.springboot.dao.BaseDao;
import com.ljq.demo.springboot.entity.ArticleEntity;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * 文章表
 * 
 * @author junqiang.lu
 * @date 2019-11-25 14:01:38
 */
@Repository
public interface ArticleDao extends BaseDao<ArticleEntity> {

    /**
     * 查詢列表
     *
     * @param queryMap
     * @return
     */
    List<ArticleEntity> queryListPage(Map<String, Object> queryMap);
	
}

4.3 所有相關類概覽

數據模型(實體類):

../demo-model/src/main/java/com/ljq/demo/springboot/entity/ArticleEntity.java
../demo-model/src/main/java/com/ljq/demo/springboot/entity/ArticleTagEntity.java
../demo-model/src/main/java/com/ljq/demo/springboot/entity/ArticleToTagEntity.java

../demo-model/src/main/java/com/ljq/demo/springboot/vo/article/ArticleListParam.java

數據持久層(DAO):

../demo-dao/src/main/java/com/ljq/demo/springboot/dao/article/ArticleTagDao.java
../demo-dao/src/main/java/com/ljq/demo/springboot/dao/article/ArticleDao.java

業務層:

../demo-service/src/main/java/com/ljq/demo/springboot/service/ArticleService.java
../demo-service/src/main/java/com/ljq/demo/springboot/service/impl/ArticleServiceImpl.java

控制層(Controller):

../demo-web/src/main/java/com/ljq/demo/springboot/web/controller/ArticleController.java

5 數據庫SQL

../doc/sql/article-database-create.sql
/*==============================================================*/
/* DBMS name:      MySQL 5.0                                    */
/* Created on:     2019/11/27 14:32:00                          */
/*==============================================================*/


drop table if exists article;

drop table if exists article_tag;

drop table if exists article_to_tag;

/*==============================================================*/
/* Table: article                                               */
/*==============================================================*/
create table article
(
   id                   bigint unsigned not null auto_increment comment '文章 id,主鍵',
   title                varchar(100) not null default '' comment '文章標題',
   content              varchar(5000) not null default '' comment '文章內容',
   primary key (id)
)
ENGINE = InnoDB
CHARSET = UTF8MB4;

alter table article comment '文章表';

/*==============================================================*/
/* Table: article_tag                                           */
/*==============================================================*/
create table article_tag
(
   id                   bigint unsigned not null auto_increment comment '文章標籤 id,主鍵',
   tag_name             varchar(20) not null default '' comment '標籤名稱',
   primary key (id)
)
ENGINE = InnoDB
CHARSET = UTF8MB4;

alter table article_tag comment '文章標籤表';

/*==============================================================*/
/* Table: article_to_tag                                        */
/*==============================================================*/
create table article_to_tag
(
   id                   bigint unsigned not null auto_increment comment '文章-標籤關聯表 id,主鍵',
   article_id           bigint unsigned not null default 0 comment '文章 id',
   tag_id               bigint unsigned not null default 0 comment '標籤 id',
   primary key (id)
)
ENGINE = InnoDB
CHARSET = UTF8MB4;

alter table article_to_tag comment '文章-標籤關聯表';

測試數據:

../doc/sql/article-database-test.sql
-- 批量插入文章標籤
INSERT INTO `article_tag`(`tag_name`) VALUES
    ('初級'),
		('中級'),
		('高級'),
		('超高級'),
		('spring'),
		('springBoot'),
		('springMVC');

-- 批量插入文章
INSERT INTO `article` (`title`, `content`) VALUES
    ('好風光', '今天天氣好晴朗,處處好風光'),
		('冰雨', '冷冷的冰雨在我臉上胡亂地拍,你就像一個劊子手把我出賣'),
		('學習', '好好學習,天天向上'),
		('靜夜思', '窗前明月光,疑是地上霜。舉頭望明月,低頭思故鄉。'),
		('冬日裏的一把火', '你就像那一把火,熊熊火焰燃燒了我'),
		('演員', '簡單點,說話的方式簡單點。遞進的情緒請省略,你又不是個演員'),
		('小蘋果', '你是我的小丫小蘋果,怎麼愛你都不嫌多'),
		('雨一直下', '雨一直下,氣氛不算融洽');


-- 批量給文章添加標籤
INSERT INTO `article_to_tag` (`article_id`, `tag_id`) VALUES
    (1,1),
    (1,2),
    (1,4),
    (2,3),
    (2,5),
    (3,6),
    (4,7),
    (5,1),
    (5,2),
    (5,3),
    (6,4),
    (6,1),
    (6,5),
    (6,7),
    (7,6),
    (7,1),
    (8,3),
    (8,6),
    (8,7),
    (8,4);
    

6 測試結果

請求接口:

http://127.0.0.1:8088/api/article/list?currPage=1&direction=desc&pageLimit=5&properties=id

後臺日誌:

2019-11-27 16:00:33 | INFO  | http-nio-8088-exec-4 | com.ljq.demo.springboot.web.acpect.LogAspectLogAspect.java 68| [AOP-LOG-START]
	requestMark: 04822886-af60-47ac-966f-0d8d6ea8c7fe
	requestIP: 127.0.0.1
	contentType:application/x-www-form-urlencoded
	requestUrl: http://127.0.0.1:8088/api/article/list
	requestMethod: GET
	requestParams: currPage = [1];direction = [desc];pageLimit = [5];properties = [id];
	targetClassAndMethod: com.ljq.demo.springboot.web.controller.ArticleController#list
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.dao.article.ArticleDao.queryListPage_COUNTBaseJdbcLogger.java 159| ==>  Preparing: SELECT count(0) FROM (SELECT a.`id`, a.`title`, a.`content` FROM article a LEFT JOIN `article_to_tag` att ON att.article_id = a.id LEFT JOIN `article_tag` at ON at.id = att.tag_id WHERE 1 = 1 GROUP BY a.id) table_count 
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.dao.article.ArticleDao.queryListPage_COUNTBaseJdbcLogger.java 159| ==> Parameters: 
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.dao.article.ArticleDao.queryListPage_COUNTBaseJdbcLogger.java 159| <==      Total: 1
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.dao.article.ArticleDao.queryListPageBaseJdbcLogger.java 159| ==>  Preparing: SELECT a.`id`, a.`title`, a.`content` FROM article a LEFT JOIN `article_to_tag` att ON att.article_id = a.id LEFT JOIN `article_tag` at ON at.id = att.tag_id WHERE 1 = 1 GROUP BY a.id order by id desc LIMIT ? 
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.dao.article.ArticleDao.queryListPageBaseJdbcLogger.java 159| ==> Parameters: 5(Integer)
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| ====>  Preparing: SELECT at.`id`, at.`tag_name` FROM `article_to_tag` att LEFT JOIN `article_tag` at ON at.id = att.tag_id LEFT JOIN `article` a ON a.id = att.article_id WHERE a.id = ? 
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| ====> Parameters: 8(Long)
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| <====      Total: 4
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| ====>  Preparing: SELECT at.`id`, at.`tag_name` FROM `article_to_tag` att LEFT JOIN `article_tag` at ON at.id = att.tag_id LEFT JOIN `article` a ON a.id = att.article_id WHERE a.id = ? 
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| ====> Parameters: 7(Long)
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| <====      Total: 2
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| ====>  Preparing: SELECT at.`id`, at.`tag_name` FROM `article_to_tag` att LEFT JOIN `article_tag` at ON at.id = att.tag_id LEFT JOIN `article` a ON a.id = att.article_id WHERE a.id = ? 
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| ====> Parameters: 6(Long)
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| <====      Total: 4
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| ====>  Preparing: SELECT at.`id`, at.`tag_name` FROM `article_to_tag` att LEFT JOIN `article_tag` at ON at.id = att.tag_id LEFT JOIN `article` a ON a.id = att.article_id WHERE a.id = ? 
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| ====> Parameters: 5(Long)
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| <====      Total: 3
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| ====>  Preparing: SELECT at.`id`, at.`tag_name` FROM `article_to_tag` att LEFT JOIN `article_tag` at ON at.id = att.tag_id LEFT JOIN `article` a ON a.id = att.article_id WHERE a.id = ? 
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| ====> Parameters: 4(Long)
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.d.a.ArticleTagDao.queryTagsByArticleIdBaseJdbcLogger.java 159| <====      Total: 1
2019-11-27 16:00:33 | DEBUG | http-nio-8088-exec-4 | c.l.d.s.dao.article.ArticleDao.queryListPageBaseJdbcLogger.java 159| <==      Total: 5
2019-11-27 16:00:33 | INFO  | http-nio-8088-exec-4 | c.l.d.springboot.service.impl.ArticleServiceImplArticleServiceImpl.java 46| 查詢耗時: 18
2019-11-27 16:00:33 | INFO  | http-nio-8088-exec-4 | com.ljq.demo.springboot.web.acpect.LogAspectLogAspect.java 76| [AOP-LOG-END]
	<200 OK,ApiResult(code=1000, msg=成功, data=PageInfo{pageNum=1, pageSize=5, size=5, startRow=1, endRow=5, total=8, pages=2, list=Page{count=true, pageNum=1, pageSize=5, startRow=0, endRow=5, total=8, pages=2, reasonable=false, pageSizeZero=false}[ArticleEntity(id=8, title=雨一直下, content=雨一直下,氣氛不算融洽, tagList=[ArticleTagEntity(id=3, tagName=高級), ArticleTagEntity(id=6, tagName=springBoot), ArticleTagEntity(id=7, tagName=springMVC), ArticleTagEntity(id=4, tagName=超高級)]), ArticleEntity(id=7, title=小蘋果, content=你是我的小丫小蘋果,怎麼愛你都不嫌多, tagList=[ArticleTagEntity(id=6, tagName=springBoot), ArticleTagEntity(id=1, tagName=初級)]), ArticleEntity(id=6, title=演員, content=簡單點,說話的方式簡單點。遞進的情緒請省略,你又不是個演員, tagList=[ArticleTagEntity(id=4, tagName=超高級), ArticleTagEntity(id=1, tagName=初級), ArticleTagEntity(id=5, tagName=spring), ArticleTagEntity(id=7, tagName=springMVC)]), ArticleEntity(id=5, title=冬日裏的一把火, content=你就像那一把火,熊熊火焰燃燒了我, tagList=[ArticleTagEntity(id=1, tagName=初級), ArticleTagEntity(id=2, tagName=中級), ArticleTagEntity(id=3, tagName=高級)]), ArticleEntity(id=4, title=靜夜思, content=窗前明月光,疑是地上霜。舉頭望明月,低頭思故鄉。, tagList=[ArticleTagEntity(id=7, tagName=springMVC)])], prePage=0, nextPage=2, isFirstPage=true, isLastPage=false, hasPreviousPage=false, hasNextPage=true, navigatePages=8, navigateFirstPage=1, navigateLastPage=2, navigatepageNums=[1, 2]}, extraData=null, timestamp=1574841633357),{Content-Type=[application/json]}>

7 參考文檔推薦

官方文檔 MyBatis Pagination - PageHelper

官方文檔 How to use PageHelper

官方文檔 PageHelper integration with Spring Boot

8 Github 源碼

Gtihub 源碼地址 : https://github.com/Flying9001/springBootDemo

個人公衆號:404Code,分享半個互聯網人的技術與思考,感興趣的可以關注.
404Code

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章