当前位置:网站首页>Recursive query of multi-level menu data
Recursive query of multi-level menu data
2022-07-05 21:26:00 【Ouch, hello o_ O hi】
1. Prepare tables and data
DROP TABLE IF EXISTS `sys_menu_test`;
CREATE TABLE `sys_menu_test` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT ' classification id',
`name` char(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT ' Category name ',
`pId` bigint NULL DEFAULT NULL COMMENT ' Parent classification id',
`showStatus` tinyint NULL DEFAULT 1 COMMENT ' Whether or not shown [0- No display ,1 Show ]',
`sort` int NULL DEFAULT 0 COMMENT ' Sort ',
`icon` char(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT ' Icon address ',
PRIMARY KEY (`id`) USING BTREE,
INDEX `pId_index`(`pId`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1437 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = ' Menu information table ' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of sys_menu_test
-- ----------------------------
INSERT INTO `sys_menu_test` VALUES (1, ' China ', 0, 1, 1, NULL);
INSERT INTO `sys_menu_test` VALUES (2, ' The United States ', 0, 1, 2, NULL);
INSERT INTO `sys_menu_test` VALUES (3, ' Canada ', 0, 1, 3, NULL);
INSERT INTO `sys_menu_test` VALUES (4, ' Anhui Province ', 1, 1, 1, NULL);
INSERT INTO `sys_menu_test` VALUES (5, ' Jiangsu Province ', 1, 1, 2, NULL);
INSERT INTO `sys_menu_test` VALUES (6, ' Zhejiang Province ', 1, 1, 3, NULL);
INSERT INTO `sys_menu_test` VALUES (7, ' Xuzhou City ', 5, 1, 1, NULL);
INSERT INTO `sys_menu_test` VALUES (8, ' Hefei ', 4, 1, 1, NULL);
INSERT INTO `sys_menu_test` VALUES (9, ' Lu'an City ', 4, 1, 2, NULL);
INSERT INTO `sys_menu_test` VALUES (10, ' Jin'an District ', 9, 1, 1, NULL);
INSERT INTO `sys_menu_test` VALUES (11, ' Yu'an District ', 9, 1, 2, NULL);
INSERT INTO `sys_menu_test` VALUES (12, ' High-tech zone ', 8, 1, 3, NULL);
INSERT INTO `sys_menu_test` VALUES (13, ' Sungang town ', 10, 1, 1, NULL);
INSERT INTO `sys_menu_test` VALUES (14, ' Chunshu town ', 10, 1, 2, NULL);
INSERT INTO `sys_menu_test` VALUES (15, ' Shuxi Lake ', 12, 1, 3, NULL);
INSERT INTO `sys_menu_test` VALUES (16, ' hangzhou ', 6, 1, 1, NULL);
INSERT INTO `sys_menu_test` VALUES (17, ' lake ', 16, 1, 1, NULL);
INSERT INTO `sys_menu_test` VALUES (18, ' Lingyin Temple ', 17, 1, 1, NULL);
2. Create entity class
package com.mozheng.manageframe.entity;
import lombok.Data;
import lombok.ToString;
import java.util.List;
/** * @Description: Menu entity class * @Author yizhixiansheng * @Date 2021/6/30 */
@Data
@ToString
public class MenuTest{
private static final long serialVersionUID = 1L;
/** * menu id */
private Long id;
/** * Menu name */
private String name;
/** * Parent menu id */
private Long pId;
/** * Whether or not shown [0- No display ,1 Show ] */
private Integer showStatus;
/** * Sort */
private Integer sort;
/** * Icon address */
private String icon;
/** * Submenu collection */
private List<MenuTest> children;
}
3. establish sql Query statement xml file
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mozheng.manageframe.mapper.MenuMapper">
<!-- Query all -->
<select id="listInfo" resultType="com.mozheng.manageframe.entity.MenuTest">
select id,`name`,pId,showStatus,sort,icon from sys_menu_test
</select>
</mapper>
4. establish mapper Interface
package com.mozheng.manageframe.mapper;
import com.mozheng.manageframe.entity.MenuTest;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface MenuMapper {
List<MenuTest> listInfo();
}
5. Create business layer interface
package com.mozheng.manageframe.service;
import com.mozheng.manageframe.entity.MenuTest;
import java.util.List;
public interface MenuService {
List<MenuTest> listInfo();
}
6. Create a business layer interface implementation class
package com.mozheng.manageframe.service.Impl;
import com.mozheng.manageframe.entity.MenuTest;
import com.mozheng.manageframe.mapper.MenuMapper;
import com.mozheng.manageframe.service.MenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
@Service
@Transactional
public class MenuServiceImpl implements MenuService {
@Override
public List<MenuTest> listInfo() {
// Get all menus
List<MenuTest> allMenu = menuMapper.listInfo();
// Get all parent nodes as 0 The node of , Root node
List<MenuTest> rootMenu = allMenu
.stream()
.filter(item -> item.getPId().equals(0L))
.collect(Collectors.toList());
// Set submenu for root menu
rootMenu.forEach(menuTest -> menuTest.setChildren(getChildList(menuTest.getId(), allMenu)));
// Sort according to the order field
rootMenu.sort(Comparator.comparing(MenuTest::getSort));
return rootMenu;
}
/** * according to id, Get its collection of child nodes * @param id Parent node id * @param allMenu All menu lists * @return java.util.List<com.mozheng.manageframe.entity.MenuTest> * @author yizhixiansheng * @create 2021/6/30 **/
private List<MenuTest> getChildList(Long id, List<MenuTest> allMenu) {
// Get all the child nodes under the passed node
List<MenuTest> childList = allMenu
.stream()
.filter(menuTest -> menuTest.getPId().equals(id))
.collect(Collectors.toList());
// When there is no child node under the transmitted node , Then exit recursion
if (Objects.isNull(childList) || childList.size() <= 0) {
return new ArrayList<>();
}
// Continue to recursive
childList.forEach(menuTest -> menuTest.setChildren(getChildList(menuTest.getId(), allMenu)));
// Sort according to the order field
childList.sort(Comparator.comparing(MenuTest::getSort));
return childList;
}
}
7. Create test class
package com.mozheng.manageframe;
import com.alibaba.fastjson.JSONObject;
import com.mozheng.manageframe.entity.Menu;
import com.mozheng.manageframe.entity.MenuTest;
import com.mozheng.manageframe.service.MenuService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class ManageframeApplicationTests {
@Autowired
private MenuService menuService;
@Test
void contextLoads() {
List<MenuTest> menuTestList = menuService.listInfo();
System.out.println(JSONObject.toJSON(menuTestList));
}
}
Look at the results
[{
"children":[{
"children":[{
"children":[{
"children":[{
"children":[],"name":" Shuxi Lake ","pId":12,"showStatus":1,"id":15,"sort":3}],"name":" High-tech zone ","pId":8,"showStatus":1,"id":12,"sort":3}],"name":" Hefei ","pId":4,"showStatus":1,"id":8,"sort":1},{
"children":[{
"children":[{
"children":[],"name":" Sungang town ","pId":10,"showStatus":1,"id":13,"sort":1},{
"children":[],"name":" Chunshu town ","pId":10,"showStatus":1,"id":14,"sort":2}],"name":" Jin'an District ","pId":9,"showStatus":1,"id":10,"sort":1},{
"children":[],"name":" Yu'an District ","pId":9,"showStatus":1,"id":11,"sort":2}],"name":" Lu'an City ","pId":4,"showStatus":1,"id":9,"sort":2}],"name":" Anhui Province ","pId":1,"showStatus":1,"id":4,"sort":1},{
"children":[{
"children":[],"name":" Xuzhou City ","pId":5,"showStatus":1,"id":7,"sort":1}],"name":" Jiangsu Province ","pId":1,"showStatus":1,"id":5,"sort":2},{
"children":[{
"children":[{
"children":[{
"children":[],"name":" Lingyin Temple ","pId":17,"showStatus":1,"id":18,"sort":1}],"name":" lake ","pId":16,"showStatus":1,"id":17,"sort":1}],"name":" hangzhou ","pId":6,"showStatus":1,"id":16,"sort":1}],"name":" Zhejiang Province ","pId":1,"showStatus":1,"id":6,"sort":3}],"name":" China ","pId":0,"showStatus":1,"id":1,"sort":1},{
"children":[],"name":" The United States ","pId":0,"showStatus":1,"id":2,"sort":2},{
"children":[],"name":" Canada ","pId":0,"showStatus":1,"id":3,"sort":3}]

边栏推荐
- Five layer network protocol
- Wood board ISO 5660-1 heat release rate mapping test
- Aitm2-0002 12s or 60s vertical combustion test
- vant 源码解析之 utils/index.ts 工具函数
- 使用WebAssembly在浏览器端操作Excel
- Learning notes of SAS programming and data mining business case 19
- WPF gets the control in the datagridtemplatecolumn of the specified row and column in the DataGrid
- 张丽俊:穿透不确定性要靠四个“不变”
- Sitge joined the opengauss open source community to jointly promote the ecological development of the database industry
- Dictionary tree simple introductory question (actually blue question?)
猜你喜欢

面试官:并发编程实战会吗?(线程控制操作详解)

EasyExcel的讀寫操作

使用WebAssembly在浏览器端操作Excel

Zhang Lijun: la pénétration de l’incertitude dépend de quatre « invariants»

Influence of oscilloscope probe on signal source impedance

Using webassembly to operate excel on the browser side

Why can't Chinese software companies produce products? Abandon the Internet after 00; Open source high-performance API gateway component of station B | weekly email exclusive to VIP members of Menon w

EN 438-7 laminated sheet products for building covering decoration - CE certification

Explain various hot issues of Technology (SLB, redis, mysql, Kafka, Clickhouse) in detail from the architecture

【案例】定位的运用-淘宝轮播图
随机推荐
Zhang Lijun: penetrating uncertainty depends on four "invariants"
Which securities company is better and which platform is safer for stock account opening
2022-07-03-cka- latest feedback from fans
Zhang Lijun: la pénétration de l’incertitude dépend de quatre « invariants»
MySQL InnoDB Architecture Principle
Get JS of the previous day (timestamp conversion)
驱动壳美国测试UL 2043 符合要求有哪些?
LeetCode_ Hash table_ Difficulties_ 149. Maximum number of points on the line
What should I do to prepare for the interview algorithm position during school recruitment?
MQ----activeMq
[daily training] 729 My schedule I
有些事情让感情无处安放
The reason why the ncnn converted model on raspberry pie 4B always crashes when called
uni-app 蓝牙通信
When a user logs in, there is often a real-time drop-down box. For example, entering an email will @qq com,@163. com,@sohu. com
Realize the function of verifying whether the user has completed login when browsing the page
张丽俊:穿透不确定性要靠四个“不变”
Two ways to realize video recording based on avfoundation
Chapter 05_ Storage engine
Arcgis\qgis no plug-in loading (no offset) mapbox HD image map