1. 程式人生 > 實用技巧 >mybatis儲存過程實現三、四,插入、刪除使用者資訊和角色關聯資訊

mybatis儲存過程實現三、四,插入、刪除使用者資訊和角色關聯資訊

1. 首先看一下資料庫要完成的儲存過程(我用的資料庫是DBeaver,這裡也給出Navicat for Mysql中的儲存過程實現,兩個不同軟體程式碼實現不太一樣)

Navicat for Mysql中儲存過程程式碼:

插入使用者資訊和角色關聯資訊:

drop procedure if exists `insert_user_and_roles`;

create procedure `insert_user_and_roles`(
    OUT userId BIGINT,
    IN userName VARCHAR(50),
    IN userPassword VARCHAR(50
), IN userEmail VARCHAR(50), IN userInfo TEXT, IN headImg BLOB, OUT createTime DATETIME, IN roleIds VARCHAR(200) ) BEGIN -- 設定當前時間 SET createTime = NOW(); -- 插入時間 INSERT INTO sys_user (user_name,user_password,user_email,user_info,head_img,create_time) VALUES (userName,userPassword,userEmail,userInfo,headImg,createTime);
-- 獲取自增主鍵 SELECT LAST_INSERT_ID() INTO userId; -- 儲存使用者和角色關係資料 SET roleIds = CONCAT(',',roleIds,','); INSERT INTO sys_user_role (user_id,role_id) SELECT userId ,id from sys_role where INSTR(roleIds,CONCAT(',',id,','))>0; END

刪除使用者資訊和角色關聯資訊:

-- 第四個儲存過程
-- 刪除使用者資訊和角色關聯資訊
drop procedure if exists `delete_user_by_id`;

create procedure `delete_user_by_id`(IN userId BIGINT) BEGIN DELETE FROM sys_user_role where user_id = userId; DELETE FROM sys_user where id = userId; END

DBeaver中儲存過程程式碼:

插入使用者資訊和角色關聯資訊:

create procedure `insert_user_and_roles`(
    OUT userId BIGINT,
    IN userName VARCHAR(50),
    IN userPassword VARCHAR(50),
    IN userEmail VARCHAR(50),
    IN userInfo TEXT,
    IN headImg BLOB,
    OUT createTime DATETIME,
    IN roleIds VARCHAR(200)
)
BEGIN
-- 設定當前時間
SET createTime = NOW();
-- 插入時間
INSERT INTO sys_user 
(user_name,user_password,user_email,user_info,head_img,create_time)
VALUES
(userName,userPassword,userEmail,userInfo,headImg,createTime);
-- 獲取自增主鍵
SELECT LAST_INSERT_ID() INTO userId;
-- 儲存使用者和角色關係資料
SET roleIds = CONCAT(',',roleIds,',');
INSERT INTO sys_user_role (user_id,role_id)
SELECT userId ,id from sys_role 
where INSTR(roleIds,CONCAT(',',id,','))>0;
END
drop procedure if exists `insert_user_and_roles`;

刪除使用者資訊和角色關聯資訊:

create procedure `delete_user_by_id`(IN userId BIGINT)
BEGIN
DELETE FROM sys_user_role where user_id = userId;
DELETE FROM sys_user  where id = userId;
END
-- 第四個儲存過程
-- 刪除使用者資訊和角色關聯資訊
drop procedure if exists `delete_user_by_id`;

注意:這裡務必注意,先執行第一部分程式碼在執行第二部分的程式碼,不然執行過程會出如下錯誤:

執行完畢後會出現相應的儲存過程:

這樣,第一步基礎就打好了。(千萬注意,在實現mybatis之前必須要實現此儲存過程,不然就會出現如下錯誤:### Cause: java.sql.SQLException: Parameter number 2 is not an OUT parameter,這個問題折磨了我兩天,頭禿,難過到窒息,最後實現了此儲存過程後報錯才消失)

第一步基礎打好了之後,接下來進行java程式碼配置。

2. UserMapper.xml中程式碼:

<insert id="insertUserAndRoles" statementType="CALLABLE">
        {
        call insert_user_and_roles
        (
        #{user.id, mode = OUT, jdbcType = BIGINT},
        #{user.userName , mode = IN},
        #{user.userPassword , mode = IN},
        #{user.userEmail , mode = IN},
        #{user.userInfo , mode = IN},
        #{user.headImg , mode = IN,jdbcType = BLOB},
        #{user.createTime , mode = OUT,jdbcType = TIMESTAMP},
        #{roleIds,mode = IN}
        )
        }
    </insert>

<delete id="deleteUserById" statementType="CALLABLE">
        {
        call delete_user_by_id
        (
        #{userId, mode = IN}
        )
        }
    </delete>

注意:這裡insert標籤中引數要和儲存過程中引數順序保持一致,不然出現報錯的情況。;例如我修改程式碼如下:

<insert id="insertUserAndRoles" statementType="CALLABLE">
        {
        call insert_user_and_roles
        (
        #{user.id, mode = OUT, jdbcType = BIGINT},
        #{user.createTime , mode = OUT,jdbcType = TIMESTAMP},
        #{user.userName , mode = IN},
        #{user.userPassword , mode = IN},
        #{user.userEmail , mode = IN},
        #{user.userInfo , mode = IN},
        #{user.headImg , mode = IN,jdbcType = BLOB},
        #{roleIds,mode = IN}
        )
        }
    </insert>

那麼執行後會出現下面報錯:

3. 介面如下:

/*
    * 儲存使用者資訊和角色關聯資訊
    * */
    int insertUserAndRoles(@Param("user")SysUser user,@Param("roleIds")String roleIds);

    /*
    * 根據使用者 id 刪除使用者和使用者的角色資訊
    * */
    int deleteUserById(Long id);

4. 測試程式碼如下:

@Test
    public  void testInsertUserAndRoles(){
        SqlSession sqlSession = getSqlSession();
        try{
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            SysUser user = new SysUser();
            user.setUserName("test2");
            user.setUserPassword("123456");
            user.setUserEmail("ccb.com");
            user.setUserInfo("test2 info");
            user.setHeadImg(new byte[]{1,2,3});
            //插入使用者資訊和角色關聯資訊
            userMapper.insertUserAndRoles(user,"1,2");
            sqlSession.commit();
            userMapper.deleteUserById(user.getId());
            Assert.assertNotNull(user.getId());
            Assert.assertNotNull(user.getCreateTime());
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

測試結果如下:

至此,第s三、四個儲存過程結束。