mybatis调用存储过程

  现在通过调用数据库的存储过程,实现这样一种功能:有一张表p_user,当传入参数为0时,返回表中女性记录的数量,否则,返回表中男性记录的数量。
 
创建数据表并插入数据:

1
2
3
4
5
6
7
8
9
create table p_user(
id int primary key auto_increment,
name varchar(10),
sex char(2)
);
insert into p_user(name,sex) values('A',"男");
insert into p_user(name,sex) values('B',"女");
insert into p_user(name,sex) values('C',"男");

image_1b4glot05ei18ik1i0u10631n6n9.png-14.5kB

创建存储过程,查询得到男性或女性的数量,如果传入的是0就女性否则是男性:

1
2
3
4
5
6
7
8
9
10
DELIMITER $
CREATE PROCEDURE mybatis.get_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='女' INTO user_count;
ELSE
SELECT COUNT(*) FROM mybatis.p_user WHERE p_user.sex='男' INTO user_count;
END IF;
END
$

创建实体类User:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class PUser {
private String id;
private String name;
private String sex;
//getters and setters
@Override
public String toString() {
return "PUser [id=" + id + ", name=" + name + ", sex=" + sex + "]";
}
public PUser(String id, String name, String sex) {
super();
this.id = id;
this.name = name;
this.sex = sex;
}
public PUser() {
super();
}
}

创建映射文件userMapper.xml:

1
2
3
4
5
6
7
8
9
10
11
12
<?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.mybatis.test8.userMapper">
<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>

编写测试类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Test {
private SqlSessionFactory sessionFactory;
private SqlSession session;
@Before
public void init(){
//读取配置文件
String resource = "conf.xml";
InputStream is = this.getClass().getClassLoader().getResourceAsStream(resource);
//创建SqlSessionFactory和SqlSession
sessionFactory = new SqlSessionFactoryBuilder().build(is);
session = sessionFactory.openSession();
}
@After
public void free(){
session.commit();
session.close();
}
@org.junit.Test
public void getCount() {
String statement = "com.mybatis.test8.userMapper"+".getCount";
Map<String,Integer> map = new HashMap<>();
map.put("sex_id", 1);
session.selectOne(statement, map);
int userCount = map.get("user_count");
System.out.println(userCount);
}
}

运行结果:

image_1b4gnq23tgll1aqei2b1u9oi19.png-23kB

注意点:

  1. 在映射文件中,需要配置select节点的statementType属性为CALLABLE,且要使用parameterMap属性映射一个存放参数的parameterMap。
  2. 需要定义parameterMap,其id与select节点的parameterMap属性一致,type指定parameterMap真实类型为java.util.Map,其中的parameter节点以键值对的形式存放参数,property属性需要和定义在存储过程中的参数名一致。