maven mybatis实现递归查询和使用存储过程

本文引用网站:https://mp.weixin.qq.com/s/rZXNTi3wi0dAsQ6k47Lw_g

项目源码包含可以运行的代码和数据库表,下载地址:https://download.csdn.net/download/liqi_q/10447884

本文主要介绍部门管理功能的后台程序,其实都是常规代码,我们重点关注两点:1.递归调用,2.存储过程调用

递归调用

由于部门的层级不可控,因此如果我想要获取所有部门的完整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
    }
]

存储过程调用

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

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字段,就能拿到相应的调用结果了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值