当前位置:网站首页>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}]
边栏推荐
- LeetCode_ Hash table_ Difficulties_ 149. Maximum number of points on the line
- Viewrootimpl and windowmanagerservice notes
- AITM2-0002 12s或60s垂直燃烧试验
- js常用方法封装
- wpf 获取datagrid 中指定行列的DataGridTemplateColumn中的控件
- Pytorch实战——MNIST数据集手写数字识别
- Simple interest mode - evil Chinese style
- What should I do to prepare for the interview algorithm position during school recruitment?
- Influence of oscilloscope probe on signal source impedance
- POJ 3414 pots (bfs+ clues)
猜你喜欢
基于 Ingress Controller 在集群外访问 Zadig 自测环境(最佳实践)
Deployment of Jenkins under win7
Add ICO icon to clion MinGW compiled EXE file
MQ----activeMq
Display DIN 4102-1 Class B1 fire test requirements
Feng Tang's "spring breeze is not as good as you" digital collection, logged into xirang on July 8!
Pytoch practice -- MNIST dataset handwritten digit recognition
让开发效率飞速提升的跨端方案
Evolution of zhenai microservice underlying framework from open source component encapsulation to self-development
Haas506 2.0 development tutorial - Alibaba cloud OTA - PAC firmware upgrade (only supports versions above 2.2)
随机推荐
Sophomore personal development summary
selenium 获取dom内属性值的方法
Explain various hot issues of Technology (SLB, redis, mysql, Kafka, Clickhouse) in detail from the architecture
Teach yourself to train pytorch model to Caffe (I)
int GetMonth( ) const throw( );后面的throw( )什么意思?
selenium 获取dom内验证码图片
[daily training -- Tencent select 50] 89 Gray code (only after seeing the solution of the problem)
Five layer network protocol
面试官:并发编程实战会吗?(线程控制操作详解)
uni-app 蓝牙通信
MQ----activeMq
Cross end solution to improve development efficiency rapidly
vant 源码解析 event.ts 事件处理 全局函数 addEventListener详解
How to send samples when applying for BS 476-7 display? Is it the same as the display??
Sequence alignment
Display DIN 4102-1 Class B1 fire test requirements
事项研发工作流全面优化|Erda 2.2 版本如“七”而至
Zhang Lijun: la pénétration de l’incertitude dépend de quatre « invariants»
秋招将临 如何准备算法面试、回答算法面试题
Aitm 2-0003 horizontal combustion test