Fork me on GitHub

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

测试结果如下:

 

 至此,第一个存储过程结束。

posted @ 2020-12-24 16:06  叶语婷  阅读(1076)  评论(0编辑  收藏  举报