需求:在删除父节点时子节点也要一并删除,子节点可以单独删除
注意:当表中有外键关系时,这种方式可能不行,可能会报错!!!!!!
效果图1:删除父节点
效果图2:子节点
前端代码:
<!-- 行内工具栏 -->
<script type="text/html" id="listBar">
<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
</script>
</script>
//监听行工具事件
table.on('tool(TableList)', function(obj){
var layEvent = obj.event,
data = obj.data;
switch(layEvent) {
case 'del':
deleteDept(data);
break;
case 'edit':
edit(data);
break;
}
});
// 删除
function deleteDept(data){
// 判断有没有子节点
var aa = '';
$.post({
// 判断有没有父节点下有没有子节点
url: "/dept/isNodeChildrens",
data: {"id" : data.id},
async: false,
success:function (result) {
if (result.success){
aa = '确定删除【'+data.title+'】和其子部门吗?';
}else{
aa = '确定删除【'+data.title+'】吗?';
}
}
})
layer.confirm(aa,{icon:3, title:'提示信息'},function(index){
$.post("/dept/deletedept",{
id : data.id,
},function(data){
if (data.code == 200){
layer.msg(data.msg);
tableIns.reload();
//刷新左侧部门数
window.parent.left.dateTree.reload();
}else{
layer.msg(data.msg);
}
layer.close(index);
})
});
}
</script>
后端代码:
@RestController
@RequestMapping("dept")
public class DeptController {
@Autowired
private DeptService deptService;
// 判断有没有父节点下有没有子节点
@RequestMapping("isNodeChildrens")
public Map<String,Object>isNodeChildrens(Integer id){
Map<String,Object>map=new HashMap<>();
List<Integer>idlist=deptService.isNodeChildrens(id);
if(idlist.size()>0){
//返回状态码用于提示框
map.put("success",true);
}
return map;
}
//删除部门
@RequestMapping("deletedept")
public ResultObj deletedept(Integer id){
try {
deptService.deletedept(id);
return ResultObj.DELETE_SUCCESS;
} catch (BindingException e) {
e.printStackTrace();
return ResultObj.DELETE_ERROR;
}
}
}
在DeptMapper.xml中SQL语句
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xxx.xx.mapper.DeptMapper">
<delete id="deletedept">
delete from sys_dept where id=#{id} or pid=#{id}
</delete>
<select id="isNodeChildrens" resultType="int">
select * from sys_dept d where d.pid = #{id}
</select>
</mapper>