ibatis调用存储过程(带输出参数的存储过程)

时间:2021-07-04 21:41:20

1、首先创建一个存储过程,一个入参(String seqName),一个出参(Integer seqValue),其实这个就是获取下一个ID的值,因为在mysql中不支持sequence,于是写了个存储(函数)过程

  1. CREATE DEFINER=`root`@`localhost` FUNCTION `get_seq_nextval`(p_seqname varchar(50)) RETURNS int(11)
  2. begin
  3. /*
  4. 参数:
  5. seqname:序列名
  6. 返回值:
  7. 未知整数
  8. 功能
  9. 这个序列的当前序列值
  10.  
  11. 创建人:蒋福龙
  12.  
  13. 时间:2010-11-4
  14. */
  15. declare v_id integer;
  16. declare v_count integer;
  17.  
  18. select count(id)into v_count from sys_seq where seq_name=p_seqname;
  19.  
  20. if v_count =0 then
  21. insert into sys_seq(id,seq_name) values(1,p_seqname);
  22. set v_id=1;
  23. else
  24. update sys_seq set id=id+1 where seq_name=p_seqname;
  25. select id into v_id from sys_seq where seq_name=p_seqname;
  26. end if;
  27. return v_id;
  28. end;
复制代码

2、在SqlMap中


  1. <!-- 获取下一个sequence -->
  2. <parameterMap id="get_seq_nextval_map" class="java.util.Map">
  3.        <parameter property="seqValue" javaType="int" jdbcType="INTEGER"
  4.            mode="OUT" />
  5.        <parameter property="seqName" javaType="string" jdbcType="VARCHAR"
  6.            mode="IN" />
  7.     </parameterMap>
  8.     <procedure id="get_seq_nextval" parameterMap="get_seq_nextval_map">
  9.        { ? = call get_seq_nextval(?) }
  10.   </procedure>  
复制代码

注意上班的mode,IN表示入参,OUT标识出参,还有个INOUT。


注意:在SqlMap.xml文件中<parameterMap>中参数的顺序跟<Procedure>中”?”的顺序一致。


如:seqValue,seqName。对应{ ? = call get_seq_nextval(?) },一一对应就行了。


3、在java中


  1. public Integer get_seq_nextval(String string) throws SQLException {
  2.   HashMap<String, Object> hm = new HashMap<String, Object>();
  3.   hm.put("seqName", string);
  4.   hm.put("seqValue",new Integer(1));
  5.   super.find("get_seq_nextval", hm);
  6.   Integer result = (Integer) hm.get("seqValue");//获取存储过程返回的值
  7.   return result;
  8. }