自联表同一张表中级联删除和移动实现

来源:互联网 发布:免费淘客软件 编辑:程序博客网 时间:2024/05/18 03:44

1.如下图:

1.1.选择要移动的节点
这里写图片描述
1.2.选择要移动到的节点
这里写图片描述

2.表结构:

CREATE TABLE `sys_organization` (  `id` bigint(20) NOT NULL AUTO_INCREMENT,  `name` varchar(100) DEFAULT NULL,  `parent_id` bigint(20) DEFAULT NULL,  `parent_ids` varchar(100) DEFAULT NULL,  `available` tinyint(1) DEFAULT '0',  PRIMARY KEY (`id`),  KEY `idx_sys_organization_parent_id` (`parent_id`),  KEY `idx_sys_organization_parent_ids` (`parent_ids`)) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

3.删除逻辑

 public void deleteOrganization(Long organizationId) {        // 1.查找到当前的组织        Organization organization = findOne(organizationId);        // 2.删除当前的组织        final String deleteSelfSql = "delete from sys_organization where id=?";        jdbcTemplate.update(deleteSelfSql, organizationId);        // 3.删除以当前组织开头的组织        final String deleteDescendantsSql = "delete from sys_organization where parent_ids like ?";        jdbcTemplate.update(deleteDescendantsSql, organization.makeSelfAsParentIds() + "%");    }

4.移动组织

@Override    public void move(Organization source, Organization target) {        // 1.把 target 当做 source 的父元素        // 1.1.设置 source 的 parent_id 为 target 的 id        // 1.2.设置 source  parent_ids 为 target.makeSelfAsParentIds() 的值        // 2.修改 source 子元素的 parent_ids        // 3.因为 source 子元素的直接父元素是不变的,所以在修改的时候,不能修改它 parent_ids 最后的那个元素,所以替换的时候也是需要注意的        // 比如:source 子元素的 a 原来的 parent_ids 是 0/1/2/4/        // 那么在修改的时候,最后的 4/ 是不用动的,这个时候只需要替换的是 0/1/2/ 这一部分        String moveSourceSql = "update sys_organization set parent_id=?,parent_ids=? where id=?";        jdbcTemplate.update(moveSourceSql, target.getId(), target.makeSelfAsParentIds(), source.getId());        String moveSourceDescendantsSql = "update sys_organization set parent_ids=concat(?, substring(parent_ids, length(?))) where parent_ids like ?";        jdbcTemplate.update(moveSourceDescendantsSql, target.makeSelfAsParentIds(), source.makeSelfAsParentIds().substring(1), source.makeSelfAsParentIds() + "%");    }

0 0