怎样使用MyBatis轻松实现递归查询与存储过程调用

发布时间:2021-11-10 11:02:57 作者:柒染
来源:亿速云 阅读:206

怎样使用MyBatis轻松实现递归查询与存储过程调用,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

递归调用

由于部门的层级不可控,因此如果我想要获取所有部门的完整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字段,就能拿到相应的调用结果了。

看完上述内容,你们掌握怎样使用MyBatis轻松实现递归查询与存储过程调用的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. mybatis调用oracle存储过程
  2. PHP 调用存储过程

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mybatis

上一篇:php如何把整数设置为浮点数

下一篇:Django中的unittest应用是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》