阅读完需:约 4 分钟
项目中你是否会遇到这样的问题?菜单数据全写在一张表里,而我们需要用数组将这些数据存下来并交给前端大佬,问题的关键就是,我们怎么做才能将一级菜单数据—二级菜单数据—三级菜单数据······一一对应呢?
递归调用
由于部门的层级不可控,因此如果我想要获取所有部门的完整json的话,就要采用递归调用,使用Java代码处理递归有点low,刚好MyBatis的ResultMap中的collection可以很方便的解决这个问题,核心代码如下:
<resultMap id="BaseResultMap" type="org.sang.bean.Department">
<id property="id" column="id"/>
<result column="name" property="name"/>
<result column="parentId" property="parentId"/>
<result column="isParent" property="isParent"/>
<collection property="children" ofType="org.sang.bean.Department" select="org.sang.mapper.DepartmentMapper.getDepByPid" column="id">
</collection>
</resultMap>
<select id="getDepByPid" resultMap="BaseResultMap">
select d1.*from department d1 where d1.`parentId`=#{pid} AND d1.enabled=true;
</select>
每一个Department中都有一个children属性,getDepByPid方法的返回结果是一个BaseResultMap,BaseResultMap中的collection又将调用getDepByPid方法,通过这种方式我们可以快速实现一个递归调用。
Mapper中只需要定义如下方法即可:
List<Department> getDepByPid(Long pid);
[
{
"id": 1,
"name": "股东会",
"parentId": -1,
"enabled": true,
"children": [
{
"id": 4,
"name": "董事长",
"parentId": 1,
"enabled": true,
"children": [
{
"id": 5,
"name": "总经理",
"parentId": 4,
"enabled": true,
"children": [
{
"id": 8,
"name": "财务部",
"parentId": 5,
"enabled": true,
"children": [],
"parent": false
}],
"parent": true
}
],
"parent": true
}
],
"parent": true
}
]
数据库结构(数据不一样,但结构是一样的):
Department的pojo:
public class Department {
private Integer id;
private String name;
private Integer parentId;
private String deppath;
private Boolean enabled;
private Boolean isparent;
private List<Department> children=new ArrayList<>();
private Integer result;
}
存储过程调用
什么是存储过程呢?
存储过程就是作为可执行对象存放在数据库中的一个或多个SQL命令。
通俗来讲:存储过程其实就是能完成一定操作的一组SQL语句。
那为什么要用存储过程呢?
1.存储过程只在创造时进行编译,以后每次执行存储过程都不需再重新编译,而一般SQL语句每执行一次就编译一次,所以使用存储过程可提高数据库执行速度。
2.当对数据库进行复杂操作时,可将此复杂操作用存储过程封装起来与数据库提供的事务处理结合一起使用。
3.存储过程可以重复使用,可减少数据库开发人员的工作量。
4.安全性高,可设定只有某些用户才具有对指定存储过程的使用权
例子:
USE vhr $$
DROP PROCEDURE IF EXISTS addDep $$
CREATE DEFINER=`root`@`localhost` PROCEDURE addDep (in depName VARCHAR(32),in parentId INT,in enabled boolean,out result int ,out result2 int)
begin
declare did int;
declare pDepPath varchar(64);
insert into department set name=depName,parentId=parentId,enabled=enabled;
select row_count() into result;
select last_insert_id() into did;
set result2=did;
select depPath into pDepPath from department where id=parentId;
update department set depPath=concat(pDepPath,'.',did) where id=did;
update department set isParent=true where id=parentId;
end
这里的重点是关于调用:
1.Mapper中添加如下方法:
void addDep(@Param("dep") Department department);
2.xml中写法如下:
<select id="addDep" statementType="CALLABLE">
call addDep(#{dep.name,mode=IN,jdbcType=VARCHAR},#{dep.parentId,mode=IN,jdbcType=INTEGER},#{dep.enabled,mode=IN,jdbcType=BOOLEAN},#{dep.result,mode=OUT,jdbcType=INTEGER},#{dep.id,mode=OUT,jdbcType=BIGINT})
</select>
注意statementType调用表示这是一个存储过程,mode=IN表示这是输入参数,mode=OUT表示这是输出参数,调用成功之后,在service中获取department的id和result字段,就能拿到相应的调用结果了。