通过postgresql的Ltree字段类型实现目录结构的基本操作

通过postgresql的Ltree字段类型实现目录结构的基本操作

将这种具有目录结构的excel表存储到数据库中,可以采用树型结构存储[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZLXAzpxj-1691660171264)(C:\Users\20745\AppData\Roaming\Typora\typora-user-images\image-20230810172124733.png)]

DROP TABLE IF EXISTS "public"."directory_tree";
CREATE TABLE "public"."directory_tree" ("id" varchar(100) COLLATE "pg_catalog"."default","path" "public"."ltree","name" varchar(100) COLLATE "pg_catalog"."default" NOT NULL,"description" text COLLATE "pg_catalog"."default","updated_at" timestamp(6) DEFAULT now(),"created_at" timestamp(6) DEFAULT now()
)
;-- ----------------------------
-- Records of directory_tree
-- ----------------------------
INSERT INTO "public"."directory_tree" VALUES ('04e19944aa1d3d8bc13971b4488a4e0d', '04e19944aa1d3d8bc13971b4488a4e0d', 'root', 'root', '2023-08-09 02:11:35.145821', '2023-08-09 02:11:35.145821');

上面是建一张表,并且插入一条根节点。这里我们的id是mybatisPuls提供的UUID,并且我们的path字段采用祖id+爷id+父id+子id的结构。这是处理excel表格的工具类

package com.cdcas.utils;import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.IOException;
import java.util.*;/*** @author jiao xn* @date 2023/4/20 22:44* @description*/
@Component
public class ExcelUtil {/*** 根据文件地址,读取指定 Excel 文件的内容,并以对象数组的方式返回** @param excelFilePath Excel 文件地址* @param sheetIndex 指定 Sheet 的索引值,从 0 开始* @param startLine 开始读取的行:从0开始* @param tailLine 去除最后读取的行* @return Excel 文件内容,对象数组*/public List<Map<String, String>> readExcelFile(String excelFilePath, Integer sheetIndex, Integer startLine, Integer tailLine) {Workbook workbook = this.generateWorkbook(excelFilePath);return this.readExcelSheetToObject(workbook, sheetIndex, startLine, tailLine);}/*** 从 MultipartFile 中读取 Excel 文件的内容,并以对象数组的方式返回** @param multipartFile MultipartFile 对象,一般是从前端接收* @param sheetIndex 指定 Sheet 的索引值,从 0 开始* @param startLine 开始读取的行:从0开始* @param tailLine 去除最后读取的行* @return Excel 文件内容,对象数组*/public List<Map<String, String>> readExcelFile(MultipartFile multipartFile, Integer sheetIndex, Integer startLine, Integer tailLine) {Workbook workbook = this.generateWorkbook(multipartFile);return this.readExcelSheetToObject(workbook, sheetIndex, startLine, tailLine);}/*** 生成 Workbook 对象** @param excelFilePath Excel 文件路径* @return Workbook 对象,允许为空*/private Workbook generateWorkbook(String excelFilePath) {Workbook workbook;try {File excelFile = new File(excelFilePath);workbook = WorkbookFactory.create(excelFile);} catch (IOException | InvalidFormatException e) {e.printStackTrace();throw new RuntimeException(e);}return workbook;}/*** 生成 Workbook 对象** @param multipartFile MultipartFile 对象* @return Workbook 对象*/private Workbook generateWorkbook(MultipartFile multipartFile) {Workbook workbook;try {workbook = WorkbookFactory.create(multipartFile.getInputStream());} catch (IOException | InvalidFormatException e) {e.printStackTrace();throw new RuntimeException(e);}return workbook;}/*** 读取指定 Sheet 中的数据** @param workbook Workbook 对象* @param sheetIndex 指定 Sheet 的索引值,从 0 开始* @param startLine 开始读取的行:从0开始* @param tailLine 去除最后读取的行* @return 指定 Sheet 的内容*/private List<Map<String, String>> readExcelSheetToObject(Workbook workbook,Integer sheetIndex, Integer startLine, Integer tailLine) {List<Map<String, String>> result = new ArrayList<>();Sheet sheet = workbook.getSheetAt(sheetIndex);// 获取第一行内容,作为标题内容Row titileRow = sheet.getRow(0);Map<String, String> titleContent = new LinkedHashMap<>();for (int i = 0; i < titileRow.getLastCellNum(); i++) {Cell cell = titileRow.getCell(i);titleContent.put(cell.getStringCellValue(), cell.getStringCellValue());}result.add(titleContent);// 获取正文内容Row row;for (Integer i = startLine; i < sheet.getLastRowNum() - tailLine + 1; i++) {row = sheet.getRow(i);Map<String, String> rowContent = new HashMap<>();for (Cell cell : row) {String returnStr;boolean isMergedCell  = this.isMergedCell(sheet, i, cell.getColumnIndex());if (isMergedCell) {returnStr = this.getMergedRegionValue(sheet, row.getRowNum(), cell.getColumnIndex());} else {returnStr = cell.getRichStringCellValue().getString();}rowContent.put(titileRow.getCell(cell.getColumnIndex()).getStringCellValue(), returnStr);}result.add(rowContent);}return result;}/*** 判断指定的单元格是否是合并单元格** @param sheet Excel 指定的 Sheet 表* @param row 行下标* @param column 列下标* @return 是否为合并的单元格*/private boolean isMergedCell(Sheet sheet, int row, int column) {int sheetMergeCount = sheet.getNumMergedRegions();for (int i = 0; i < sheetMergeCount; i++) {CellRangeAddress range = sheet.getMergedRegion(i);int firstColumn = range.getFirstColumn();int lastColumn = range.getLastColumn();int firstRow = range.getFirstRow();int lastRow = range.getLastRow();if(row >= firstRow && row <= lastRow && (column >= firstColumn && column <= lastColumn)){return true;}}return false;}/*** 获取合并单元格的值** @param sheet 指定的值* @param row 行号* @param column 列好* @return 合并单元格的值*/private String getMergedRegionValue(Sheet sheet, int row, int column){int sheetMergeCount = sheet.getNumMergedRegions();for(int i = 0 ; i < sheetMergeCount ; i++){CellRangeAddress ca = sheet.getMergedRegion(i);int firstColumn = ca.getFirstColumn();int lastColumn = ca.getLastColumn();int firstRow = ca.getFirstRow();int lastRow = ca.getLastRow();if(row >= firstRow && row <= lastRow && (column >= firstColumn && column <= lastColumn)) {Row fRow = sheet.getRow(firstRow);Cell fCell = fRow.getCell(firstColumn);return this.getCellValue(fCell) ;}}return null ;}/*** 获取单元格的值** @param cell Cell 对象* @return 单元格的值*/private String getCellValue(Cell cell){if(cell == null) {return "";}if(cell.getCellTypeEnum() == CellType.STRING){return cell.getStringCellValue();} else if(cell.getCellTypeEnum() == CellType.BOOLEAN){return String.valueOf(cell.getBooleanCellValue());} else if(cell.getCellTypeEnum() == CellType.FORMULA){return cell.getCellFormula() ;} else if(cell.getCellTypeEnum() == CellType.NUMERIC){return String.valueOf(cell.getNumericCellValue());}return "";}
}

下面是将生成的List<Map<String, String>> excel数据插入到excel表中的工具类

package com.cdcas;import com.cdcas.mapper.DirectoryTreeMapper;
import com.cdcas.pojo.DirectoryTree;
import com.cdcas.utils.ExcelDataUtil;
import com.cdcas.utils.ExcelUtil;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;import java.io.FileInputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Map;/*** @version 1.0* @Author zhaozhixin* @Date 2023/8/7 15:01* @注释*/   //983
@SpringBootTest
public class Test2 {/*** 替换和插入** @param parentPath* @param directoryTree*/private String Insert(String parentPath, DirectoryTree directoryTree, String name) {directoryTree.setName(name);directoryTree.setDescription(parentPath);directoryTreeMapper.insert(directoryTree);directoryTree.setPath(parentPath + "." + directoryTree.getId());directoryTreeMapper.updateDirectoryTree(directoryTree);return directoryTree.getId();}/*** 通过名称查询父路径** @param name* @return*/private String getParentPathByName(String name) {DirectoryTree parent = directoryTreeMapper.getOneByName(name);return parent.getPath();}@Testpublic void get() {String path = directoryTreeMapper.getPath(1);System.out.println(path);}@Autowiredprivate ExcelUtil excelUtil;@Autowiredprivate ExcelDataUtil excelDataUtil;@Autowiredprivate DirectoryTreeMapper directoryTreeMapper;@Testpublic void insert() throws Exception {//读取一个excelList<Map<String, String>> maps = excelUtil.readExcelFile("C:\\Users\\20745\\Desktop\\git库\\gitee\\pg-demo-itree\\src\\main\\resources\\国土规划目录树.xlsx", 0, 1, 0);maps.remove(0);System.out.println(maps);for (Map<String, String> map : maps) {String A1 = map.get("A1");String A2 = map.get("A2");String A3 = map.get("A3");String A4 = map.get("A4");String A5 = map.get("A5");String A6 = map.get("A6");String A7 = map.get("A7");String A8 = map.get("A8");String A9 = map.get("A9");StringBuilder parentPath = new StringBuilder();//用来拼接父节点idparentPath.append("04e19944aa1d3d8bc13971b4488a4e0d");//这是根节点idif (A1 != null && !"".equals(A1)) {//二级节点  根节点为rootDirectoryTree directoryTree = new DirectoryTree();String name = A1;String id = isExtis(name, directoryTree, parentPath.toString());if (id==null){}else {parentPath.append(".").append(id);}}if (A2 != null && !"".equals(A2)) {//拿到所有同名的行DirectoryTree directoryTree = new DirectoryTree();String name = A2;String id = isExtis(name, directoryTree, parentPath.toString());if (id==null){}else {parentPath.append(".").append(id);}}if (A3 != null && !"".equals(A3)) {DirectoryTree directoryTree = new DirectoryTree();String name = A3;String id = isExtis(name, directoryTree, parentPath.toString());if (id==null){}else {parentPath.append(".").append(id);}}if (A4 != null && !"".equals(A4)) {DirectoryTree directoryTree = new DirectoryTree();String name = A4;String id = isExtis(name, directoryTree, parentPath.toString());if (id==null){}else {parentPath.append(".").append(id);}}if (A5 != null && !"".equals(A5)) {DirectoryTree directoryTree = new DirectoryTree();String name = A5;String id = isExtis(name, directoryTree, parentPath.toString());if (id==null){}else {parentPath.append(".").append(id);}}if (A6 != null && !"".equals(A6)) {DirectoryTree directoryTree = new DirectoryTree();String name = A6;String id = isExtis(name, directoryTree, parentPath.toString());if (id==null){}else {parentPath.append(".").append(id);}}if (A7 != null && !"".equals(A7)) {DirectoryTree directoryTree = new DirectoryTree();String name = A7;String id = isExtis(name, directoryTree, parentPath.toString());if (id==null){}else {parentPath.append(".").append(id);}}if (A8 != null && !"".equals(A8)) {DirectoryTree directoryTree = new DirectoryTree();String name = A8;String id = isExtis(name, directoryTree, parentPath.toString());if (id==null){}else {parentPath.append(".").append(id);}}if (A9 != null && !"".equals(A9)) {DirectoryTree directoryTree = new DirectoryTree();String name = A9;String id = isExtis(name, directoryTree, parentPath.toString());if (id==null){}else {parentPath.append(".").append(id);}}}}/*** 判断一个同名的是否存在在其它数 返回当前节点id* @param name* @param directoryTree* @param parentPath*/private String isExtis(String name,DirectoryTree directoryTree,String parentPath){//最终标识  开始表明不存在boolean isExtis = false;//获取到所有的和name同名的行List<DirectoryTree> oneByNames = directoryTreeMapper.getListByName(name);//如果没有同名的直接插入if (CollectionUtils.isEmpty(oneByNames)){directoryTree.setName(name);directoryTree.setDescription(parentPath);directoryTreeMapper.insert(directoryTree);directoryTree.setPath(parentPath+"."+directoryTree.getId());directoryTreeMapper.updateDirectoryTree(directoryTree);return directoryTree.getId();}//如果有同名的,需要判断父路径是否相同String path = "";int lastIndexOf = 0;for (DirectoryTree oneByName : oneByNames) {if (oneByName!=null) {path = oneByName.getPath();lastIndexOf = path.lastIndexOf(".");}//重复的数据应该也要被插入进去  查出的父路径传入的父路径进行对比if (path.substring(0,lastIndexOf).equals(parentPath)){isExtis = true;}}//最后如果同名的数据但是父路径不相同,就需要插入进去if (!isExtis){directoryTree.setName(name);directoryTree.setDescription(parentPath);directoryTreeMapper.insert(directoryTree);directoryTree.setPath(parentPath+"."+directoryTree.getId());directoryTreeMapper.updateDirectoryTree(directoryTree);return directoryTree.getId();}return oneByNames.get(oneByNames.size()-1).getId();}//查看重复条数和 总条数@Testpublic void look() throws Exception {FileInputStream fileInputStream = new FileInputStream("C:\\Users\\20745\\Desktop\\git库\\gitee\\pg-demo-itree\\src\\main\\resources\\国土规划目录树.xlsx");List<Map<String, String>> maps = excelDataUtil.readExcel(fileInputStream);int count = 0;HashSet<String> set = new HashSet();for (Map<String, String> map : maps) {if (StringUtils.isNotBlank(map.get("A1"))) {set.add(map.get("A1"));count++;}if (StringUtils.isNotBlank(map.get("A2"))) {set.add(map.get("A2"));count++;}if (StringUtils.isNotBlank(map.get("A3"))) {set.add(map.get("A3"));count++;}if (StringUtils.isNotBlank(map.get("A4"))) {set.add(map.get("A4"));count++;}if (StringUtils.isNotBlank(map.get("A5"))) {set.add(map.get("A5"));count++;}if (StringUtils.isNotBlank(map.get("A6"))) {set.add(map.get("A6"));count++;}if (StringUtils.isNotBlank(map.get("A7"))) {set.add(map.get("A7"));count++;}if (StringUtils.isNotBlank(map.get("A8"))) {set.add(map.get("A8"));count++;}if (StringUtils.isNotBlank(map.get("A9"))) {set.add(map.get("A9"));count++;}}System.out.println(count);System.out.println(set.size());}
}

最后插入的数据大概是这样[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-449koFvW-1691660171266)(C:\Users\20745\AppData\Roaming\Typora\typora-user-images\image-20230810172712617.png)]

注意这里的path!!!!!是id拼起来的具有目录层次的!![外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UHQCBxy4-1691660171267)(C:\Users\20745\AppData\Roaming\Typora\typora-user-images\image-20230810173241809.png)]

这些关于目录树的基本操作,楼主写了一个小demo放在gitee上面了。本人不会算法,里面写的很菜见谅哈哈。喜欢的点个赞谢谢<.>! gitee地址:pg-demo-itree: 基于postgresql的Itree功能实现目录树的操作 (gitee.com)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/75910.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

NSS [CISCN 2019初赛]Love Math

# NSS [CISCN 2019初赛]Love Math 开题直接给源码 <?php error_reporting(0); //听说你很喜欢数学&#xff0c;不知道你是否爱它胜过爱flag if(!isset($_GET[c])){show_source(__FILE__); }else{//例子 c20-1$content $_GET[c];if (strlen($content) > 80) {die(&quo…

基于Python的HTTP代理爬虫开发初探

前言 随着互联网的发展&#xff0c;爬虫技术已经成为了信息采集、数据分析的重要手段。然而在进行爬虫开发的过程中&#xff0c;由于个人或机构的目的不同&#xff0c;也会面临一些访问限制或者防护措施。这时候&#xff0c;使用HTTP代理爬虫可以有效地解决这些问题&#xff0…

清风数学建模——拟合算法

拟合算法 文章目录 拟合算法概念 确定拟合曲线最小二乘法的几何解释求解最小二乘法matlab求解最小二乘法如何评价拟合的好坏计算拟合优度的代码 概念 在前面的篇幅中提到可以使用插值算法&#xff0c;通过给定的样本点推算出一定的曲线从而推算出一些想要的值。但存在一些问题…

Android学习之路(8) Activity

本节引言&#xff1a; 本节开始讲解Android的四大组件之一的Activity(活动)&#xff0c;先来看下官方对于Activity的介绍&#xff1a; 移动应用体验与桌面体验的不同之处在于&#xff0c;用户与应用的互动并不总是在同一位置开始&#xff0c;而是经常以不确定的方式开始。例如&…

【Git】分支管理

文章目录 一、理解分支二、创建、切换、合并分支三、删除分支四、合并冲突五、合并模式六、分支策略七、bug分支八、强制删除分支 努力经营当下 直至未来明朗&#xff01; 一、理解分支 HEAD指向的是master分支&#xff0c;master中指向的是最新一次的提交&#xff0c;也就是m…

基于opencv的手势控制音量和ai换脸

基于opencv的手势控制音量和ai换脸 HandTrackingModule.py import cv2 import mediapipe as mp import timeclass handDetector():def __init__(self, mode False, maxHands 2, model_complexity 1, detectionCon 0.5, trackCon 0.5):self.mode modeself.maxHands max…

QChart类用来 管理 图表的:数据序列(series)、图例(legend)和坐标轴(axis)

QChart类用来 管理 图表的&#xff1a;数据序列&#xff08;series&#xff09;、图例&#xff08;legend&#xff09;和坐标轴&#xff08;axis&#xff09; 1、数据序列类 继承关系 2、坐标轴类 的继承关系 3、图例类 什么是图例&#xff1f; 图例&#xff1a;是集中于地图…

通过LD_PRELOAD绕过disable_functions

LD_PRELOAD LD_PRELOAD是Linux/Unix系统的一个环境变量&#xff0c;它可以影响程序的运行时的链接&#xff0c;它允许在程序运行前定义优先加载的动态链接库。通过这个环境变量&#xff0c;可以在主程序和其动态链接库的中间加载别的动态链接库&#xff0c;甚至覆盖系统的函数…

Java网络编程(一)网络基础

概述 计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统、网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递 网络分类 局域网(LAN) 局域网是一种在小区域内使用的,由多台计算机组成的网络,覆盖范围…

下载安装并使用小乌龟TortoiseGit

1、下载TortoiseGit安装包 官网&#xff1a;Download – TortoiseGit – Windows Shell Interface to Githttps://tortoisegit.org/download/ 2、小乌龟汉化包 在官网的下面就有官方提供的下载包 3、安装

11. Vuepress2.x 关闭夜间模式

修改 docs/.vuepress/config.ts 配置文件 设置 themeConfig.darkMode属性详见 官网 module.exports {host: localhost, // ipport: 8099, //端口号title: 我的技术站, // 设置网站标题description: 描述&#xff1a;我的技术站,base: /, //默认路径head: [// 设置 favor.ico&a…

使用pnpm workspace管理Monorepo架构

在开发项目的过程中&#xff0c;我们需要在一个仓库中管理多个项目&#xff0c;每个项目有独立的依赖、脚手架&#xff0c;这种形式的项目结构我们称之为Monorepo&#xff0c;pnpm workspace就是管理这类项目的方案之一。 一、pnpm简介 1、pnpm概述 pnpm代表performance npm…