首页 > 代码库 > 调用存储过程
调用存储过程
1
准备数据库表和存储过程:
create table p_user(
id int primary key auto_increment,
name varchar(10),
sex varchar(20)
);
2
create table p_user( id int primary key auto_increment, name varchar(10), sex varchar(20) );
insert into p_user(name,sex) values(‘A‘,"nan"); insert into p_user(name,sex) values(‘B‘,"nv"); insert into p_user(name,sex) values(‘C‘,"nan");
#创建存储过程(查询得到男性或女性的数量, 如果传入的是0就女性否则是男性) DELIMITER $ CREATE PROCEDURE mybatis.ges_user_count(IN sex_id INT, OUT user_count INT) BEGIN IF sex_id=0 THEN SELECT COUNT(*) FROM mybatis.p_user WHERE p_user.sex=‘nv‘ INTO user_count; ELSE SELECT COUNT(*) FROM mybatis.p_user WHERE p_user.sex=‘nan‘ INTO user_count; END IF; END $
#调用存储过程 DELIMITER ; SET @user_count = 0; CALL mybatis.ges_user_count(1, @user_count); SELECT @user_count; |
创建表的实体类:
public class User {
private String id;
private String name;
private String sex;
}
<mapper namespace="com.mybatis.test7.userMapper">
<!--
查询得到男性或女性的数量, 如果传入的是0就女性否则是男性
CALL mybatis.get_user_count(1, @user_count);
-->
注意:statementtype必须修改,因为是调用存储过程
<select id="getCount" statementType="CALLABLE" parameterMap="getCountMap">
call mybatis.get_user_count(?,?)
</select>
<parameterMap type="java.util.Map" id="getCountMap">
<parameter property="sex_id" mode="IN" jdbcType="INTEGER"/>
<parameter property="user_count" mode="OUT" jdbcType="INTEGER"/>
</parameterMap>
</mapper>
测试调用:
SqlSession session=MyBatisUtils.getSession();
String statement = "com.atguigu.day03_mybaits.test8.getCountuserMapper.getUserCount";
Map<String, Integer> parameterMap = new HashMap<String, Integer>();
注意:sexid可以不和上面的sex_id一样,usercount一样
parameterMap.put("sexid", 1);
parameterMap.put("usercount", -1);
session.selectOne(statement, parameterMap);
Integer result = parameterMap.get("usercount");
System.out.println(result);
session.close();
调用存储过程