0%

10.3 MyBatis调用存储过程 10.3.4修改数据

10.3 MyBatis调用存储过程 10.3.4修改数据

在之前创建的mybatis数据库中创建一个修改tb_user表数据的存储过程。SQL脚本如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
drop procedure if exists update_user_by_id;
delimiter $$
create procedure update_user_by_id (
IN p_id int,
IN p_name varchar(18),
IN p_sex varchar(19),
IN p_age int
)
begin
update tb_user set name=p_name,sex=p_sex,age=p_age
where id=p_id;
end
$$
delimiter ;

注意

注意存储过程的参数定义,如果参数类型是varchar则一定要指定长度:IN p_name varchar(18),,如果直接写IN p_name varchar,将会创建失败.
也就是说下面的的将SQL脚本创建失败:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
drop procedure if exists update_user_by_id;
delimiter $$
create procedure update_user_by_id (
IN p_id int,
IN p_name varchar,
IN p_sex varchar(19),
IN p_age int
)
begin
update tb_user set name=p_name,sex=p_sex,age=p_age
where id=p_id;
end
$$
delimiter ;

错误提示如下:

1
2
3
4
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '
IN p_sex varchar(19),
IN p_age int
)

xml映射

1
2
3
4
5
6
7
8
9
10
11
<update
id="updateUserById"
parameterType="domain.User"
statementType="CALLABLE"> {
call update_user_by_id(
#{id,mode=IN},
#{name,mode=IN},
#{sex,mode=IN},
#{age,mode=IN})
}
</update>

mapper接口方法

1
void updateUserById(User user);

测试类

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
34
35
36
37
38
39
40
41
42
43
44
45
46
package test;
import org.apache.ibatis.session.SqlSession;
import domain.User;
import fractory.SqlSessionFratoryTools;
import mapper.UserMapper;
public class UpdateUserByIDTest {
public static void main(String[] args)
{
SqlSession sqlSession = null;
// 1.获取SqlSession实例
sqlSession = SqlSessionFratoryTools.getSqlSession();
try
{
// 2.获取Mapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 3.调用mapper接口方法进行操作
// 先找到要更新的记录
User user = userMapper.selectUserById(6);
if (user != null)
{
System.out.println("要更新的用户:" + user);
user.setName("小李子");
user.setSex("女");
user.setAge(18);
// 更新用户的信息
userMapper.updateUserById(user);
user = userMapper.selectUserById(6);
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
6
7
8
9
10
11
12
13
DEBUG [main] ==>  Preparing: {call select_user_by_id(?)} 
DEBUG [main] ==> Parameters: 6(Integer)
DEBUG [main] <== Total: 1
DEBUG [main] <== Updates: 0
要更新的用户:User [id=6, name=小李, sex=男, age=23]
DEBUG [main] ==> Preparing: { call update_user_by_id( ?, ?, ?, ?) }
DEBUG [main] ==> Parameters: 6(Integer), 小李子(String), 女(String), 18(Integer)
DEBUG [main] <== Updates: 1
DEBUG [main] ==> Preparing: {call select_user_by_id(?)}
DEBUG [main] ==> Parameters: 6(Integer)
DEBUG [main] <== Total: 1
DEBUG [main] <== Updates: 0
更新后用户的信息:User [id=6, name=小李子, sex=女, age=18]

原文链接: 10.3 MyBatis调用存储过程 10.3.4修改数据