这是我的表:
在这里插入图片描述
这是存储过程:

delimiter $$
create procedure getSexCount(in sex_id int,out sex_count int)
begin
	IF sex_id = 0 then
		select count(*) from tbl_employee where gender = '女' INTO sex_count;
	else
		select count(*) from tbl_employee where gender = '男' INTO sex_count;
	END IF;
end $$

在这里插入图片描述

这是dao接口中的方法:

// 对于带OUT返回值的存储过程,我们在java中传参一定要是map,
// 且方法返回值不能是int,long这些基本类型,只能使用引用类型。
    public Integer getGenderCount(Map<String,Integer> param); 
 // sid = 0,查女生;否则 查 男生,使用MySQL的存储过程getSexCount。

这是mapper配置文件:

<!--    
	没必要指定resultType,因为返回值封装在了map里,
	我们只需指定好map的泛型即可。
-->
    <select id="getGenderCount" parameterType="java.util.Map" statementType="CALLABLE" >
        {call getSexCount(
            #{sid,mode=IN,jdbcType=INTEGER},
            #{sexCount,mode=OUT,jdbcType=INTEGER}
        )}
    </select>

测试代码:

@Test
    public void testPro02(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
        Map<String,Integer> map = new HashMap<>();
        map.put("sid",0);
        //map.put("sexCount",-1);
        // 就算hashMap中没有添加sexCount这个key,mybatis在处理结果集时也会自动添加!
        //key的名称会根据xml中的call的参数进行确定
        mapper.getGenderCount(map);
        System.out.println("输出结果是:"+map.get("sexCount"));  //返回值13
        System.out.println("genderCount:"+genderCount);//返回null,指定了resultType也返回的是null。
    }
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐