mybatis儲存過程實現一:根據使用者 id 查詢使用者其他資訊
阿新 • • 發佈:2020-12-24
1. 首先看一下資料庫要完成的儲存過程(我用的資料庫是DBeaver,這裡也給出Navicat for Mysql中的儲存過程實現,兩個不同軟體程式碼實現不太一樣)
Navicat for Mysql中儲存過程程式碼:
-- 第一個儲存過程 -- 根據使用者id查詢用其他資訊 -- 多個輸出引數 delimiter $ drop procedure if exists `select_user_by_id`; create procedure `select_user_by_id`( IN userId BIGINT, OUT userName VARCHAR(50), OUT userPasswordVARCHAR(50), OUT userEmail VARCHAR(50), OUT userInfo TEXT, OUT headImg BLOB, OUT createTime DATETIME ) BEGIN -- 根據使用者id查詢其他資料 select user_name,user_password,user_email,user_info,head_img,create_time INTO userName,userPassword,userEmail,userInfo,headImg,createTime from sys_user where id =userId; END $ DELIMITER ;
執行後出現儲存過程函式:
DBeaver中儲存過程程式碼:
create procedure `select_user_by_id`( IN userId BIGINT, OUT userName VARCHAR(50), OUT userPassword VARCHAR(50), OUT userEmail VARCHAR(50), OUT userInfo TEXT, OUT headImg BLOB, OUT createTime DATETIME ) BEGIN -- 根據使用者id查詢其他資料select user_name,user_password,user_email,user_info,head_img,create_time INTO userName,userPassword,userEmail,userInfo,headImg,createTime from sys_user where id = userId; END
drop procedure if exists `select_user_by_id`;
注意:這裡務必注意,先執行第一部分程式碼在執行第二部分的程式碼,不然執行過程會出如下錯誤:
執行完畢後會出現相應的儲存過程:
這樣,第一步基礎就打好了。(千萬注意,在實現mybatis之前必須要實現此儲存過程,不然就會出現如下錯誤:### Cause: java.sql.SQLException: Parameter number 2 is not an OUT parameter,這個問題折磨了我兩天,頭禿,難過到窒息,最後實現了此儲存過程後報錯才消失)
第一步基礎打好了之後,接下來進行java程式碼配置。
2. UserMapper.xml中程式碼:
<select id="selectUserById" statementType="CALLABLE" useCache="false"> { call select_user_by_id( #{id,mode = IN}, #{userName,mode = OUT,jdbcType = VARCHAR}, #{userPassword,mode = OUT,jdbcType = VARCHAR}, #{userEmail,mode = OUT,jdbcType = VARCHAR}, #{userInfo,mode = OUT,jdbcType = VARCHAR}, #{headImg,mode = OUT,jdbcType = BLOB, javaType = _byte[]}, #{createTime,mode = OUT,jdbcType = TIMESTAMP} ) } </select>
3. 介面如下:
/* * 使用儲存過程查詢使用者資訊 * */ void selectUserById(SysUser user);
4. 測試程式碼如下:
@Test public void testSelectUserById(){ SqlSession sqlSession = getSqlSession(); try{ UserMapper userMapper = sqlSession.getMapper(UserMapper.class); SysUser user = new SysUser(); user.setId(1l); userMapper.selectUserById(user); Assert.assertNotNull(user.getUserName()); System.out.println("使用者名稱:"+ user.getUserName()); }finally { sqlSession.close(); } }
測試結果如下:
至此,第一個儲存過程結束。