mybatis存儲過程實現一:根據用戶 id 查詢用戶其他信息


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 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 $
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();
        }
    }

測試結果如下:

 

 至此,第一個存儲過程結束。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM