MyBatis實現遞歸查詢的方法詳解
業務場景
在項目開發過程中,往往會遇到多級菜單、分類等多層級結構數據的查詢。
for example:
請看上圖,這是一個電商項目中常見的多級類目功能,如圖所示,共分為一、二、三,共三級類目,每一個一級類目有各自的二級目錄,每個二級目錄有自己的三級目錄
再看這個例子,下圖是一個多級菜單的功能,和上面的例子類似
在這種場景下,通常我們要用遞歸進行處理。下面博主以電商項目的多級類目功能,通過MyBatis進行遞歸查詢功能說明
開發環境
名稱 | 版本 |
---|---|
IntelliJ IDEA | 2021.3.2 |
Spring Boot | 2.6.4 |
mybatis-spring-boot-starter | 2.2.2 |
數據庫
表結構
CREATE TABLE `shopping_commodity_category` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL COMMENT 'category name', `picture` varchar(255) DEFAULT NULL COMMENT 'category picture id', `superior_category` int NOT NULL DEFAULT 0 COMMENT 'superior category id', `sort_number` int NOT NULL COMMENT 'sort number', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'creation time of this record', `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'update time of this record', PRIMARY KEY (`id`), UNIQUE KEY (`superior_category`, `name`), UNIQUE KEY (`superior_category`, `sort_number`) );
字段解釋:
字段名 | 含義 |
---|---|
id | 數據表中每條數據的唯一標識符 |
name | 類目名稱 |
picture | 類目的預覽圖id(由於業務需要,這個地方保存的另一張表的文件的id,可根據需要直接存儲圖片地址),由於上級父分類沒有預覽圖,所以可以為空 |
superior_category | 上級類目的id,不能為空,如果是頂級類目,那麼他的上級類目id就為0 |
sort_number | 排序號,用於在同一級的目錄下進行排序 |
create_time | 數據的創建時間,無需關註,值是插入數據時自動通過當前時間戳填充 |
update_time | 數據的更新時間,無需關註,值是在當這條記錄被更新時自動以當前時間戳進行更新 |
約束解釋:
類型 | 用途 |
主鍵約束(id) | (顯而易見,無需贅述) |
聯合唯一約束(UNIQUE KEY (superior_category, name)) | 在同一級類目下面,限制不能有重復的類目名稱 |
聯合唯一約束(UNIQUE KEY (superior_category, sort_number)) | 在同一級類目下,限制排序號不能重復 |
由於博主這個地方業務需要,用到瞭另一張表的數據,為瞭說明問題,博主將另一張表的結構也貼出來參考
CREATE TABLE `storage_multimedia_file` ( `id` int NOT NULL AUTO_INCREMENT, `absolute_path` text NOT NULL COMMENT 'file absolute path', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'creation time of this record', `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'update time of this record', PRIMARY KEY (`id`) );
這個表很簡單,就一個主要的字段,存儲的這個文件的絕對路徑,方便後續通過IO流讀取
插入測試數據
shopping_commodity_category表 INSERT INTO shopping_commodity_category (id, name, picture, superior_category, sort_number, create_time, update_time) VALUES (1, '手機通訊', null, 0, 1, '2022-08-11 17:27:15', '2022-08-11 17:27:15'); INSERT INTO shopping_commodity_category (id, name, picture, superior_category, sort_number, create_time, update_time) VALUES (2, '手機配件', null, 1, 1, '2022-08-11 17:29:59', '2022-08-11 17:29:59'); INSERT INTO shopping_commodity_category (id, name, picture, superior_category, sort_number, create_time, update_time) VALUES (3, '手機耳機', '2', 2, 1, '2022-08-11 17:29:59', '2022-08-11 17:29:59'); INSERT INTO shopping_commodity_category (id, name, picture, superior_category, sort_number, create_time, update_time) VALUES (4, '藍牙耳機', '3', 2, 2, '2022-08-11 17:31:26', '2022-08-11 17:31:26'); INSERT INTO shopping_commodity_category (id, name, picture, superior_category, sort_number, create_time, update_time) VALUES (5, '手機殼/保護殼', '4', 2, 3, '2022-08-11 17:32:51', '2022-08-11 17:32:51'); INSERT INTO shopping_commodity_category (id, name, picture, superior_category, sort_number, create_time, update_time) VALUES (6, '手機貼膜', '5', 2, 4, '2022-08-11 17:33:44', '2022-08-11 17:33:44'); INSERT INTO shopping_commodity_category (id, name, picture, superior_category, sort_number, create_time, update_time) VALUES (7, '運營商', null, 1, 2, '2022-08-11 17:34:44', '2022-08-11 17:34:44'); INSERT INTO shopping_commodity_category (id, name, picture, superior_category, sort_number, create_time, update_time) VALUES (8, '辦號卡', '6', 7, 1, '2022-08-11 17:36:25', '2022-08-11 17:36:25'); INSERT INTO shopping_commodity_category (id, name, picture, superior_category, sort_number, create_time, update_time) VALUES (9, '傢用電器', null, 0, 2, '2022-08-11 17:36:54', '2022-08-11 17:36:54'); INSERT INTO shopping_commodity_category (id, name, picture, superior_category, sort_number, create_time, update_time) VALUES (10, '生活電器', null, 9, 1, '2022-08-11 17:37:46', '2022-08-11 17:37:46'); INSERT INTO shopping_commodity_category (id, name, picture, superior_category, sort_number, create_time, update_time) VALUES (11, '吸塵器', '7', 10, 1, '2022-08-11 17:38:55', '2022-08-11 17:38:55'); INSERT INTO shopping_commodity_category (id, name, picture, superior_category, sort_number, create_time, update_time) VALUES (12, '廚房小電', null, 9, 2, '2022-08-11 17:40:04', '2022-08-11 17:40:04'); INSERT INTO shopping_commodity_category (id, name, picture, superior_category, sort_number, create_time, update_time) VALUES (13, '電飯煲', '8', 12, 1, '2022-08-11 17:41:17', '2022-08-11 17:41:17');
storage_multimedia_file表
INSERT INTO trembling_bird.storage_multimedia_file (id, absolute_path, create_time, update_time) VALUES (1, 'D:\\files\\trembling-bird\\commodity-previews\\1.webp', '2022-08-11 16:18:49', '2022-08-11 16:18:49'); INSERT INTO trembling_bird.storage_multimedia_file (id, absolute_path, create_time, update_time) VALUES (2, 'D:\\files\\trembling-bird\\category-preview\\1.jpg', '2022-08-11 17:30:12', '2022-08-11 17:30:12'); INSERT INTO trembling_bird.storage_multimedia_file (id, absolute_path, create_time, update_time) VALUES (3, 'D:\\files\\trembling-bird\\category-preview\\2.jpg', '2022-08-11 17:31:07', '2022-08-11 17:31:07'); INSERT INTO trembling_bird.storage_multimedia_file (id, absolute_path, create_time, update_time) VALUES (4, 'D:\\files\\trembling-bird\\category-preview\\3.png', '2022-08-11 17:32:07', '2022-08-11 17:32:07'); INSERT INTO trembling_bird.storage_multimedia_file (id, absolute_path, create_time, update_time) VALUES (5, 'D:\\files\\trembling-bird\\category-preview\\4.jpg', '2022-08-11 17:33:36', '2022-08-11 17:33:36'); INSERT INTO trembling_bird.storage_multimedia_file (id, absolute_path, create_time, update_time) VALUES (6, 'D:\\files\\trembling-bird\\category-preview\\5.png', '2022-08-11 17:35:48', '2022-08-11 17:35:48'); INSERT INTO trembling_bird.storage_multimedia_file (id, absolute_path, create_time, update_time) VALUES (7, 'D:\\files\\trembling-bird\\category-preview\\6.jpg', '2022-08-11 17:38:22', '2022-08-11 17:38:22'); INSERT INTO trembling_bird.storage_multimedia_file (id, absolute_path, create_time, update_time) VALUES (8, 'D:\\files\\trembling-bird\\category-preview\\7.jpg', '2022-08-11 17:40:38', '2022-08-11 17:40:38');
關鍵代碼
實體類代碼
實體類的公共父類(因為數據庫中每個表都有共同的字段,如id,create_time,update_time,所以將這些共有的字段抽取出來放到公共的父類,讓其他實體類繼承此父類,就有瞭這些公共字段,降低代碼冗餘)
package com.fenzhimedia.commons.pojo; import lombok.Data; import java.io.Serializable; import java.time.LocalDateTime; /** * @author Yi Dai [email protected] * @since 2022/3/21 13:55 */ @Data public abstract class BasePojo implements Serializable { /** * the unique identification of this record in the database table */ protected int id; /** * creation time of this record */ protected LocalDateTime createTime; /** * update time of this record */ protected LocalDateTime updateTime; }
描述類目的實體類
package com.fenzhimedia.commons.shopping.pojo; import com.fenzhimedia.commons.pojo.BasePojo; import com.fenzhimedia.commons.storage.pojo.MultimediaFile; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.List; /** * @author Yi Dai [email protected] * @since 2022/4/23 10:43 */ @Data @EqualsAndHashCode(callSuper = true) public class CommodityCategory extends BasePojo { /** * category name */ private String name; /** * entity class encapsulating picture information */ private MultimediaFile picture; /** * used to specify the order of categories, * which is only valid under the same level category */ private Integer sortNumber; /** * sub commodity category */ private List<CommodityCategory> subCommodityCategories; }
描述文件的實體類
package com.fenzhimedia.commons.storage.pojo; import com.fenzhimedia.commons.pojo.BasePojo; import lombok.Data; import lombok.EqualsAndHashCode; /** * @author Yi Dai [email protected] * @since 2022/8/11 16:03 */ @Data @EqualsAndHashCode(callSuper = true) public class MultimediaFile extends BasePojo { private String absolutePath; }
MyBatis的mapper接口代碼
package com.fenzhimedia.shopping.mapper; import com.fenzhimedia.commons.shopping.pojo.CommodityCategory; import java.util.List; /** * @author Yi Dai [email protected] * @since 2022/8/11 16:46 */ public interface CommodityCategoryMapper { List<CommodityCategory> queryCommodityCategories(int superiorCategoryId); }
mapper映射文件代碼
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.fenzhimedia.shopping.mapper.CommodityCategoryMapper"> <select id="queryCommodityCategories" resultMap="commodityCategoryMap"> select `shopping_commodity_category`.`id` as `shopping_commodity_category_id`, `shopping_commodity_category`.`name` as `shopping_commodity_category_name`, `shopping_commodity_category`.`picture` as `shopping_commodity_category_picture`, `shopping_commodity_category`.`superior_category` as `shopping_commodity_category_superior_category`, `storage_multimedia_file`.`id` as `storage_multimedia_file_id`, `storage_multimedia_file`.`absolute_path` as `storage_multimedia_file_absolute_path` from `shopping_commodity_category` left join `storage_multimedia_file` on `shopping_commodity_category`.`picture` = `storage_multimedia_file`.`id` where `superior_category` = #{categoryId} order by `shopping_commodity_category`.`sort_number` </select> <resultMap id="commodityCategoryMap" type="commodityCategory"> <id property="id" column="shopping_commodity_category_id"/> <result property="name" column="shopping_commodity_category_name"/> <association property="picture" javaType="multimediaFile"> <id property="id" column="storage_multimedia_file_id"/> <result property="absolutePath" column="storage_multimedia_file_absolute_path"/> </association> <collection property="subCommodityCategories" ofType="commodityCategory" column="shopping_commodity_category_id" select="queryCommodityCategories"/> </resultMap> </mapper>
代碼解釋:
可以看到,queryCommodityCategories是一個類目表和文件表的左連接查詢,然後分別起瞭別名,接收一個int型的參數,為上級類目的id,當然也就是0,然後聲明一個resultMap ,將字段映射起來,都是基本操作,唯一值得註意的就是
subCommodityCategories作為一個集合,它有通過select直接調用瞭queryCommodityCategories這個查詢,而參數正是由column屬性傳遞過去的,參數的值就是當前類目的id(shopping_commodity_category_id)(有點繞),其實這樣就遞歸查詢起來瞭
那麼有的小夥伴可能會疑問,既然是已知是0,為何不直接寫道xml中,而是大費周章的,在接口上聲明一個參數,然後傳遞進來?其實這是因為後面的遞歸查詢的時候需要傳入上級分類的id,一旦寫死瞭,就隻能查詢上級分類id為0的,很顯然,達不到想要的效果
既然如此,那麼就需要業務代碼中來傳遞上級類目id這個參數,很顯然我們直接在代碼中寫死不是那麼的優雅。博主這裡為瞭更靈活,我想要實現一個如果前臺傳遞瞭上級分類id,那麼就幫他查詢指定上級類目的子級類目,如果沒有傳遞,那麼就查詢所有的類目及其子類目。所以博主是這麼處理的:
@GetMapping("/queryCommodityCategories") public ResponseBody queryCommodityCategories(@RequestParam(required = false, defaultValue = "0") int superiorCategoryId) { return commodityCategoryService.queryCommodityCategories(superiorCategoryId); }
查詢測試
返回結果
statusCode、message是通用返回實體類的結構,無需關註,查詢的數據在data中
{ "statusCode": 200, "message": null, "data": [ { "id": 1, "createTime": null, "updateTime": null, "name": "手機通訊", "picture": null, "sortNumber": null, "subCommodityCategories": [ { "id": 2, "createTime": null, "updateTime": null, "name": "手機配件", "picture": null, "sortNumber": null, "subCommodityCategories": [ { "id": 3, "createTime": null, "updateTime": null, "name": "手機耳機", "picture": { "id": 2, "createTime": null, "updateTime": null, "absolutePath": "D:\\files\\trembling-bird\\category-preview\\1.jpg" }, "sortNumber": null, "subCommodityCategories": [ ] }, { "id": 4, "createTime": null, "updateTime": null, "name": "藍牙耳機", "picture": { "id": 3, "createTime": null, "updateTime": null, "absolutePath": "D:\\files\\trembling-bird\\category-preview\\2.jpg" }, "sortNumber": null, "subCommodityCategories": [ ] }, { "id": 5, "createTime": null, "updateTime": null, "name": "手機殼/保護殼", "picture": { "id": 4, "createTime": null, "updateTime": null, "absolutePath": "D:\\files\\trembling-bird\\category-preview\\3.png" }, "sortNumber": null, "subCommodityCategories": [ ] }, { "id": 6, "createTime": null, "updateTime": null, "name": "手機貼膜", "picture": { "id": 5, "createTime": null, "updateTime": null, "absolutePath": "D:\\files\\trembling-bird\\category-preview\\4.jpg" }, "sortNumber": null, "subCommodityCategories": [ ] } ] }, { "id": 7, "createTime": null, "updateTime": null, "name": "運營商", "picture": null, "sortNumber": null, "subCommodityCategories": [ { "id": 8, "createTime": null, "updateTime": null, "name": "辦號卡", "picture": { "id": 6, "createTime": null, "updateTime": null, "absolutePath": "D:\\files\\trembling-bird\\category-preview\\5.png" }, "sortNumber": null, "subCommodityCategories": [ ] } ] } ] }, { "id": 9, "createTime": null, "updateTime": null, "name": "傢用電器", "picture": null, "sortNumber": null, "subCommodityCategories": [ { "id": 10, "createTime": null, "updateTime": null, "name": "生活電器", "picture": null, "sortNumber": null, "subCommodityCategories": [ { "id": 11, "createTime": null, "updateTime": null, "name": "吸塵器", "picture": { "id": 7, "createTime": null, "updateTime": null, "absolutePath": "D:\\files\\trembling-bird\\category-preview\\6.jpg" }, "sortNumber": null, "subCommodityCategories": [ ] } ] }, { "id": 12, "createTime": null, "updateTime": null, "name": "廚房小電", "picture": null, "sortNumber": null, "subCommodityCategories": [ { "id": 13, "createTime": null, "updateTime": null, "name": "電飯煲", "picture": { "id": 8, "createTime": null, "updateTime": null, "absolutePath": "D:\\files\\trembling-bird\\category-preview\\7.jpg" }, "sortNumber": null, "subCommodityCategories": [ ] } ] } ] } ] }
以上就是MyBatis實現遞歸查詢的方法詳解的詳細內容,更多關於MyBatis遞歸查詢的資料請關註WalkonNet其它相關文章!
推薦閱讀:
- Mybatis plus通用字段自動填充的示例
- MyBatisPlus使用@TableField註解處理默認填充時間的問題
- MP(MyBatis-Plus)實現樂觀鎖更新功能的示例代碼
- MyBatis-Plus不使用數據庫默認值的問題及解決
- mybatis-plus 新增/修改如何實現自動填充指定字段