Mybatis调用Mysql数据库存储过程
存储过程(Stored Procedure)是为了完成特定功能的SQL语句集,经编译创建并保存在数据库中,用户可通过指定存储过程的名字并给定参数(需要时)来调用执行。
如果使用Mybatis框架,那么如何调用存储过程呢?
例子:带参数并返回一个结果集
- 1、存储过程(查询当前用户的所有子部门)
DELIMITER $$
USE `pcloud_outEmployees`$$
DROP PROCEDURE IF EXISTS `sp_findChildDeptListByUserId`$$
CREATE DEFINER=`root`@`%` PROCEDURE `sp_findChildDeptListByUserId`(userId BIGINT(20))
BEGIN
DECLARE dIdStr TEXT;
DECLARE dId TEXT;
SET dIdStr = '';
#查询当前用户的所有部门Id
SET dId = (SELECT GROUP_CONCAT(d.dept_id) FROM tb_user_dept d WHERE d.user_id =userId);
#查询所有部门下的子部门Id
WHILE dId IS NOT NULL DO
IF dIdStr = '' THEN
SET dIdStr = CONCAT(dIdStr, dId);
ELSE
SET dIdStr = CONCAT(dIdStr, ',', dId);
END IF;
SELECT GROUP_CONCAT(dept_id) INTO dId FROM tb_dept WHERE FIND_IN_SET(parent_id, dId) > 0;
END WHILE;
#查询所有部门
SELECT DISTINCT d.dept_name AS `label`,d.dept_id AS `value`,d.dept_id AS id,d.parent_id AS parentId FROM tb_dept d WHERE FIND_IN_SET(d.dept_id, dIdStr) > 0;
END$$
DELIMITER ;
- 2、DAO和XML
List<DeptCas> sp_findChildDeptListByUserId(@Param("userId")Long userId);
<select id="sp_findChildDeptListByUserId" resultType="cn.pconline.pcloud.base.vo.DeptCas" statementType="CALLABLE">
call sp_findChildDeptListByUserId(#{userId,mode=IN,jdbcType=BIGINT})
</select>
参考文档:
https://www.cnblogs.com/xiaoxi/p/6606011.html
https://www.jiweichengzhu.com/article/2435813e67d14d0b9d003031ad07559a