调用存储过程
创建表
CREATE TABLE `p_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(10) DEFAULT NULL,
`sex` char(2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
insert into p_user(name,sex) values('A',"Ma");
insert into p_user(name,sex) values('B',"Fe");
insert into p_user(name,sex) values('C',"Ma");
insert into p_user(name,sex) values('D',"Ma");
insert into p_user(name,sex) values('E',"Ma");
insert into p_user(name,sex) values('F',"Fe");
创建存储过程,并调用
$
BEGIN
IF sex_id=0 THEN
SELECT COUNT(*) FROM mybatis.p_user WHERE p_user.sex='Fe' INTO user_count;
ELSE
SELECT COUNT(*) FROM mybatis.p_user WHERE p_user.sex='Ma' INTO user_count;
END IF;
END
$
mysql> SET @user_count = 0;
CALL mybatis.ges_user_count(1, @user_count);
SELECT @user_count;
Query OK, 0 rows affected
Query OK, 1 row affected
+-------------+
| @user_count |
+-------------+
| 4 |
+-------------+
1 row in set
使用mybatis来实现此功能
配置mapper
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bart.mybatis.mapper.procedureMapper">
<!--
存储过程查询
parameterMap:传入的参数是一个Map
statementType:CALLABLE调用存储过程查询
-->
<select id="getUserCount" parameterMap="getUserCountMap" statementType="CALLABLE">
CALL mybatis.ges_user_count(?,?)
</select>
<!--
输入参数对应的map
map.put("sexid", 0);
map.put("userCount", -1);//任意给定默认值
-->
<parameterMap type="java.util.Map" id="getUserCountMap">
<parameter property="sexid" mode="IN" jdbcType="INTEGER"/>
<parameter property="userCount" mode="OUT" jdbcType="INTEGER"/>
</parameterMap>
</mapper>
配置conf
把mapper加入进来
<mapper resource="com/bart/mybatis/mapper/procedureMapper.xml"/>
测试
@Test
public void getUserCount(){
SqlSessionFactory sessionFactory = DBUtil.getSessionFactory();
SqlSession session = sessionFactory.openSession();
// 创建存储参数的Map
Map<String, Integer>map = new HashMap<String, Integer>();
map.put("sexid", 1);
map.put("userCount", -1);//任意给定默认值
String statement ="com.bart.mybatis.mapper.procedureMapper.getUserCount";
session.selectOne(statement, map);
//获得存储过程执行完后的userCount的值
Integer count = map.get("userCount");
System.out.println("查询到的值:"+count);
session.close();
}
结果:
查询到的值:4
mybatis调用存储过程成功
总结
- 传入的是一个Map,查询返回的是Integer,作为调用存储过程函数
- 存储过程查询
- parameterMap:传入的参数是一个Map
- statementType:CALLABLE调用存储过程查询
- 配置parameterMap
输入参数对应应该map里面的值
map.put("sexid", 0);
map.put("userCount", -1);//任意给定默认值
- type:java.util.Map
- property:对应的map中key值
- mode:IN/OUT表示是作为输入参数还是输出参数
-
jdbcType:数据库对应的类型