您的位置:首页 > 其它

mybatis-如何调用存储过程

2018-01-10 16:10 645 查看
最近因为公司的需求,所以整理了一下mybatis调用存储过程的资料分享给大家。

1.创建存储过程 例如

存储过程中 in,out, in out 表示;

in 是参数的默认模式,这种模式就是在程序运行的时候已经具有值,在程序体中值不会改变。

out模式定义的参数只能在过程体内部赋值,表示该参数可以将某个值传递回调用他的过程

in out 表示高参数可以向该过程中传递值,也可以将某个值传出去

DROP PROCEDURE IF EXISTS `proc_adder`;

CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_adder`(IN a int, IN b int, OUT sum int)
BEGIN
#Routine body goes here...
DECLARE c int;
if a is null then set a = 0;
end if;

if b is null then set b = 0;
end if;
set sum  = a + b;

select sum; #查询,返回sum结果集
END


2.存储过程写完之后就是与mybatis框架进行交接 

     给a 和 b 赋值 为 1 和 2 如果结果集 大于1就返回 0 给页面

/**
* @param request
* @param map
* @return
*/
@RequestMapping("getUserDeman")
@ResponseBody
public ModelMap getUserDeman(HttpServletRequest request, ModelMap map) {
Map<String, Object> maps = new HashMap<String, Object>();
maps.put("a", "1");
maps.put("b", "2");
//存储过程
DxwCustomerInterview interview=dxwMonService.storedProcedure(maps);
System.out.println(interview.getSum());}
if (interview != null && interview.getTyp() > 1)
{
map.put("data","0");
}
else
{
map.put("data","1");
}
return map;
}


  3.mybatis的xml 操作

<resultMap id="CustomerInterview" type="com.web.bean.dxw.DxwCustomerInterview" >
<result column="sum" property="sum"/>
</resultMap>


call proc_adder 执行这个存储过程 
mode=IN a和b  说明 a和b 是传的参数; 
mode=OUT sum 说明 sum 可以返回的值; 
jdbcType=INTEGER 是对应数据库类型 与上面创建存储过程的类型一致
例如 :
IN a int 说明  jdbcType=INTEGER;
IN a varchar(50) 说明 jdbcType=VARCHAR;
resultMap="CustomerInterview";返回值的内容在这里

<select id="storedProcedure"  resultMap="CustomerInterview" parameterType="java.util.Map" statementType="CALLABLE">
{call hlj.customer_interview(
#{a,jdbcType=INTEGER,mode=IN},
#{b,jdbcType=INTEGER,mode=IN},
#{sum,jdbcType=INTEGER,mode=OUT}
)}
</select>
发现其实和基本的 mybatis 数据库调用是一样的,只是赋值的时候多了一些参数配置
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: