Mybatis - 存储过程

    xiaoxiao2021-12-14  18

    存储过程没有返回值,不要尝试接收存储过程返回值:

    -- 正确; deviceImagesExtendDao.getCheckedDeviceCount(map); -- 之后代码直接使用map即可。如果需要返回值,map里面有对应的inout型或out型参数。 -- 错误; Map<String, Object> checkedDeviceCount = deviceImagesExtendDao.getCheckedDeviceCount(map); -- checkedDeviceCount 将会为null !!!

    【1】带有in /out 参数

    create PROCEDURE get_user_count(in sex_id INT,OUT user_count INT) BEGIN IF sex_id = 0 THEN SELECT COUNT(*) FROM p_user WHERE p_user.sex="女" into user_count; ELSE SELECT COUNT(*) FROM p_user WHERE p_user.sex="男" INTO user_count; END IF; END Navicat 下 调用存储过程 : set @user_count = 0; CALL get_user_count(1,@user_count); SELECT @user_count; result as follows :


    【2】xml配置

    <select id="getUserCount" parameterMap="getUserCountMap" statementType="CALLABLE"> <!-- set the statmentType callable--> call get_user_count(?,?) </select> <!-- type --java.util.Map--> <parameterMap type="java.util.Map" id="getUserCountMap"> <!-- mod distinguish the in or out or inout --> <parameter property="sexId" jdbcType="INTEGER" mode="IN"/> <parameter property="userCount" jdbcType="INTEGER" mode="OUT"/> </parameterMap>

    或者xml配置如下:

    <select id="getUserCount" parametertype="hashmap" statementType="CALLABLE" resultType="hashmap"> <!-- set the statmentType callable--> {call get_user_count( #{sexId,jdbcType=INTEGER,mode=IN}, #{userCount,jdbcType=INTEGER,mode=OUT} )} </select>

    | 这里需要说明一下xml配置与存储过程参数注意事项 :

    ① 如果两个参数不同类型,务必按照存储过程参数类型次序进行xml配置;

    ② 如果两个参数同样类型,将会按照xml配置依次传参;mybatis或者mysql不会按照jdbcType给你自动甄别。

    ③ select标签可以不加resultType,即使加了也不会有返回值接收(存储过程无返回值)


    【3】Test

    @Test public void getUserCount(){ SqlSession session = MybatisUtils.getFactory().openSession(); String statement = "com.web.mapper.userMapper.getUserCount"; Map<String, Integer> paramMap = new HashMap<String, Integer>(); paramMap.put("sexId", 0); paramMap.put("userCount", 1); Integer userCount = session.selectOne(statement,paramMap); /* commit by yourself*/ session.commit(); System.out.println("effect rows.."+userCount); System.out.println("存储过程输出结果。。。"+paramMap.get("userCount")); session.close(); } result as follows : effect rows..null /*存储过程无返回值,当然是null !!!*/ 存储过程输出结果。。。3
    转载请注明原文地址: https://ju.6miu.com/read-964824.html

    最新回复(0)