10.3 MyBatis调用存储过程 10.3.3根据id查询数据返回对象

10.3 MyBatis调用存储过程 10.3.3根据id查询数据返回对象

创建存储过程

在之前创建的mybatis数据库中创建一个根据id查询tb_user表对应数据的存储过程,SQL脚本如下:

1
2
3
4
5
6
7
8
drop procedure if exists select_user_by_id;
delimiter $$
create procedure select_user_by_id(IN in_id INTEGER)
begin
select id,name,sex,age from tb_user where id=in_id;
end
$$
delimiter ;

创建映射标签

UserMapper.xml中加入调用名为”select_user_by_id“的存储过程的select元素,如下代码所示:

1
2
3
4
5
6
7
8
<select
id="selectUserById"
parameterType="int"
resultType="domain.User"
statementType="CALLABLE"> {
call select_user_by_id(#{id,mode=IN})
}
</select>

mapper接口方法

1
User selectUserById(Integer id);

测试类

/MyProcedureTest/src/test/SelectByIdTest.java
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
package test;

import org.apache.ibatis.session.SqlSession;
import domain.User;
import fractory.SqlSessionFactoryTools;
import mapper.UserMapper;

public class SelectByIdTest {
public static void main(String[] args) {
SqlSession sqlSession = null;
// 1.获取SqlSession实例
sqlSession = SqlSessionFactoryTools.getSqlSession();
try {
// 2.获取Mapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 3.调用mapper接口方法进行操作
User user = userMapper.selectUserById(1);
System.out.println(" " + user);
// 5.提交事务
sqlSession.commit();
} catch (Exception e) {
// 6.出错回滚
sqlSession.rollback();
e.printStackTrace();
} finally {
// 7.关闭会话
if (sqlSession != null) {
sqlSession.close();
}
}
}
}

运行效果

1
2
3
4
5
DEBUG [main] ==>  Preparing: {call select_user_by_id(?)} 
DEBUG [main] ==> Parameters: 1(Integer)
DEBUG [main] <== Total: 1
DEBUG [main] <== Updates: 0
User [id=1, name=小明, sex=男, age=21]