当前位置:网站首页>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}]
边栏推荐
- 办公遇到的问题--
- SQL common syntax records
- Aitm 2-0003 horizontal combustion test
- Test of incombustibility of cement adhesives BS 476-4
- Objects in the list, sorted by a field
- POJ 3414 pots (bfs+ clues)
- Mode - "Richter replacement principle"
- SYSTEMd resolved enable debug log
- @Validated基础参数校验、分组参数验证和嵌套参数验证
- ArcGIS栅格重采样方法介绍
猜你喜欢
示波器探头对信号源阻抗的影响
JMeter installation under win7
[case] Application of element display and hiding -- element mask
Display DIN 4102-1 Class B1 fire test requirements
Parker驱动器维修COMPAX控制器维修CPX0200H
使用WebAssembly在浏览器端操作Excel
Learning robots have no way to start? Let me show you the current hot research directions of robots
Introduction of ArcGIS grid resampling method
Explain various hot issues of Technology (SLB, redis, mysql, Kafka, Clickhouse) in detail from the architecture
让开发效率飞速提升的跨端方案
随机推荐
123456
Vant source code parsing event Detailed explanation of TS event processing global function addeventlistener
Careercup its 1.8 serial shift includes problems
@Validated basic parameter verification, grouping parameter verification and nested parameter verification
Determine the best implementation of horizontal and vertical screens
显示器要申请BS 476-7 怎么送样?跟显示屏一样吗??
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
MySQL 千万数据量深分页优化, 拒绝线上故障!
树莓派4B上ncnn转换出来的模型调用时总是崩溃(Segment Fault)的原因
【日常训练--腾讯精选50】89. 格雷编码(看题解才会的)
Talk about my fate with some programming languages
vant 源码解析 event.ts 事件处理 全局函数 addEventListener详解
Problems encountered in office--
What are the requirements of UL 2043 test for drive housing in the United States?
Realize the function of verifying whether the user has completed login when browsing the page
基于vertx-web-sstore-redis的改造实现vertx http应用的分布式session
Parker driver maintenance COMPAX controller maintenance cpx0200h
Longest swing sequence [greedy practice]
学习机器人无从下手?带你体会当下机器人热门研究方向有哪些
有些事情让感情无处安放