13.递归查询与存储过程调用

 

后台程序也都是常规代码,我们重点关注两点:

  1. 递归调用
  2. 存储过程调用

13.1 递归调用

由于部门的层级不可控,因此如果我想要获取所有部门的完整 json 的话,就要采用递归调用,这里的递归调用我们可以利用 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
    }
]

13.2 存储过程调用

存储过程调用比较简单,以添加部门为例,如下:

  1. Mapper 中添加如下方法:
void addDep(@Param("dep") Department department);
  1. 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 字段,就能拿到相应的调用结果了。

扫码关注微信公众号 江南一点雨,回复 2TB,获取超 2TB Java 学习教程~

喜欢这篇文章吗?扫码关注公众号【江南一点雨】【江南一点雨】专注于 SPRING BOOT+微服务以及前后端分离技术,每天推送原创技术干货,关注后回复 JAVA,领取松哥为你精心准备的 JAVA 干货!

本文遵守 Attribution-NonCommercial 4.0 International 许可协议。 Attribution-NonCommercial 4.0 International