mybatis调用mysql的存储过程(procedure),实现查询操作(student表中的某个年级中的总人数 select (1) 或者 select (*))

时间:2023-03-08 21:15:54

step1:在mysql cmd中新建存储过程:

drop procedure if exists queryCountByGrade ;

delimiter // -- 定义存储过程结束符号为//
create procedure queryCountByGrade(IN gradenameinput INT(),OUT counts int()
begin
select count(*) into counts from student where grade = gradenameinput;end // delimiter ; --重新定义存储过程的结束符号是分号

step2:编写StudentMapper.xml文件

<!-- 通过mybatis调用存储过程procedure,来实现查询功能  ,statementType="CALLABLE" -->
<select id="queryCountByGradeWithProcedure" statementType="CALLABLE" parameterType="HashMap">
CALL queryCountByGrade( #{gradenameinput,mode=IN,jdbcType=VARCHAR}, #{counts,mode=OUT,jdbcType=INTEGER}
                //queryCountByGrade:就是mysql存储过程名称
) </select>

step3:编写StudentManager.java 接口文件

//使用存储过程实现查询的操作
void queryCountByGradeWithProcedure(Map<String,Object> mapp);

step4:测试函数

/**
* 使用存储过程实现数量的查询,某个年级的人数
* @param args
* @throws IOException
*/
/**
* 带转换器
* @throws IOException
*/
public static void throughProcedureToQueryCountByGradeName() throws IOException
{
Reader reader = Resources.getResourceAsReader("conf.xml"); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sessionFactory.openSession();//就是session名字即可 StudentManager studentManager = session.getMapper(StudentManager.class); Map<String ,Object>mapp = new HashMap();//通过Map给存储过程,指定输入参数gradenameinput
         //gradenameinput和counts都是mysql中存储过程定义时候的,名称,跟CALL queryCountByGrade(#{},#{})里的是一致的
mapp.put("gradenameinput", 5);//指定存储过程的出入参数gradenameinput,是5 studentManager.queryCountByGradeWithProcedure(mapp);//调用存储过程 Object obj = mapp.get("counts");//获取存储过程的输出参数:counts System.out.println(obj);
session.close(); }//queryonestudentwithconverser()