MyBatis调用MySQL存储过程
Posted yifansj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis调用MySQL存储过程相关的知识,希望对你有一定的参考价值。
业务背景:
机构ID:省(360000),市级(360100),区县级(360101)
输入一个机构ID(可能是区,也可能是市)在sys_ability_warning_rule表中查询对应机构ID,
如:输入360305(区县级),
如果表中有对应ID,则直接返回360305,
如果没有对应ID,则查询有没有市级ID(360300),如果有,则返回360300,
如果市级ID也没有,则查询省级ID(360000),如果有,则返回360000,
如果省级ID也没有,则返回(000000)
方法一:循环法
CREATE PROCEDURE `getSchWarnRule`(IN organiz VARCHAR(20),OUT organiz_rule VARCHAR(20)) BEGIN DECLARE sqlStr VARCHAR(4000) DEFAULT ‘‘; DECLARE leg INT DEFAULT 6; REPEAT SET sqlStr = CONCAT("select count(*) into @count from sys_ability_warning_rule wr where wr.organiz = ‘", organiz, "‘"); SET @sql2 = sqlStr; PREPARE stat1 FROM @sql2; EXECUTE stat1; IF @count = 0 THEN SET leg = leg - 2; SET organiz = RPAD(LEFT(organiz,leg),6,0); END IF; UNTIL @count>=1 OR leg = 0 END REPEAT; SET organiz_rule = organiz; END
方法二:递归法
DROP PROCEDURE IF EXISTS `getSchWarnRule2`; -- organiz 机构 -- organiz_rule 有效机构 CREATE PROCEDURE getSchWarnRule2(IN organiz VARCHAR(20),OUT organiz_rule VARCHAR(20)) BEGIN DECLARE sqlStr VARCHAR(4000) DEFAULT ‘‘; DECLARE organiz_rule2 VARCHAR(20) DEFAULT ‘‘; DECLARE organiz2 VARCHAR(20) DEFAULT RPAD(organiz,6,0); IF organiz2!=‘000000‘ THEN SET sqlStr = CONCAT("select count(*) into @count from sys_ability_warning_rule wr where wr.organiz = ‘", organiz2, "‘"); SET @sql2 = sqlStr; PREPARE stat1 FROM @sql2; EXECUTE stat1; IF @count=0 THEN call getSchWarnRule2(LEFT(organiz,CHAR_LENGTH(organiz)-2), organiz_rule2); SET organiz_rule = organiz_rule2; ELSEIF @count>=1 THEN SET organiz_rule = organiz; END IF; END IF; END;
MyBatis调用:
WarnRuleMapper.java 接口
public interface WarnRuleMapper extends BaseMapper<SysAbilityWarningRule> { public String getSchWarnRule(Map map); }
WarnRuleMapper.xml
<select id="getSchWarnRule" parameterType="java.util.Map" resultType="java.lang.String" statementType="CALLABLE" > { call getSchWarnRule( #{organiz,mode=IN,jdbcType=VARCHAR}, #{organiz_rule,mode=OUT,jdbcType=VARCHAR} ) } </select>
然后再用Service层调用就OK了。
以上是关于MyBatis调用MySQL存储过程的主要内容,如果未能解决你的问题,请参考以下文章
使用mybatis查询mysql数据库 先调用存储过程,然后再inner join 存储过程返回的临时表出错 高手帮忙看下!