步骤一
调用存储过程,首先,在mysql-8中创建一个存储过程。
代码执行过程如下:
根据性别统计人数(mysql)
##设置分隔符为 $$
mysql> delimiter $$
##创建存储过程
mysql> create procedure queryCountBySexWithProcedure(IN psex int,OUT pcount int)
-> begin
-> select count(*) into pcount from person where sex=psex;
-> end$$
mysql> delimiter ;
##执行存储过程
mysql> call queryCountBySexWithProcedure(1,@num);
##查看参数的值(out)
mysql> select @num;
步骤二(关键)
然后,在mybatis中配置调用存储过程的SQL语句。
<!-- 输入参数为hashmap -->
<select id="queryCountBySexWhitProcedure" statementType="CALLABLE" parameterType="HashMap">
{
CALL queryCountBySexWithProcedure
(
#{sex,jdbcType=INTEGER,mode=IN},
#{count,jdbcType=INTEGER,mode=OUT}
)
}
</select>
1.通过 statementType=“CALLABLE” 设置SQL的执行方式是存储过程。
2.存储过程的输入参数 sex需要通过HashMap来指定。在使用时通过 put() 方法来传入。
3.存储过程的返回结果存放在OUT参数中,其输出参数 count及其值会被存放到HashMap中,所以要获取OUT参数的值要通过HashMap的 get() 方法。
4.通过CALL 调用存储过程,存储过程名字和数据库中保存一致。
步骤三
配置mapper接口
//存储过程无返回值,用void
void queryCountBySexWhitProcedure(HashMap<String, Object> hashMap);
步骤四
测试执行
//patameterType为HashMap,调用存储过程
static void queryCountBySexWhitProcedure() throws IOException{
String resource = "config.xml";
InputStream inputStream =Resources.getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = factory.openSession();
/*动态代理方式调用接口*/
PersonMapper personMapper = session.getMapper(PersonMapper.class);
HashMap<String, Object> personMap = new HashMap<String, Object>();
//通过hashmap向存储过程传入参数
personMap.put("sex", 1);
//执行存储过程
personMapper.queryCountBySexWhitProcedure(personMap);
//获取存储过程的输出参数,注意,该参数不是我们put进去的,而是存储过程执行完成后,其out参数被存放进来
int count = (int)personMap.get("count");
System.out.println(count);
}
注意:HashMap的key和存储过程的参数的对应关系
存储过程 无论输入参数是什么值,语法上都需要 用map来传递该值;