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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值