10.3 MyBatis调用存储过程 10.3.5删除数据
在之前创建的mybatis
数据库中创建一个删除tb_user
表数据的存储过程。SQL
脚本如下所示:
1 2 3 4 5 6 7 8
| drop procedure if exists delete_user_by_id; delimiter $$ create procedure delete_user_by_id(IN p_id integer) begin delete from tb_user where id=p_id; end $$ delimiter ;
|
mapper.xml映射
1 2 3 4 5
| <delete id="deleteUserById" parameterType="int" statementType="CALLABLE"> {call delete_user_by_id(#{id,mode=IN})} </delete>
|
mapper接口方法
1
| void deleteUserById(Integer id);
|
测试类
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 DeleteUserByIdTest { public static void main(String[] args) { SqlSession sqlSession = null; sqlSession = SqlSessionFratoryTools.getSqlSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.selectUserById(6); if (user != null) { System.out.println(" 删除:" + user); userMapper.deleteUserById(6); } sqlSession.commit(); } catch (Exception e) { sqlSession.rollback(); e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } } }
|
运行结果
1 2 3 4 5 6 7 8
| 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] DEBUG [main] ==> Preparing: {call delete_user_by_id(?)} DEBUG [main] ==> Parameters: 6(Integer) DEBUG [main] <== Updates: 1
|
执行测试类时,先调用”select_user_by_id
“存储过程查询id
为6
的User
数据,如果找到该数据,则调用”delete_user_by_id
“存储过程将该User
数据删除。
原文链接: 10.3 MyBatis调用存储过程 10.3.5删除数据