彻底理解存储过程及在Mybatis中的调用

1、什么是存储过程

1.1 定义

储存过程是实现某个特定功能的一组sql语句集,是经过编译后方存储在数据库中。当出现大量的事务回滚或经常出现某条语句时,使用存储过程的效率往往比批量操作要高得多。

1.2 语法(此处以MySql为例)

创建表student以此为例

create table student
(
  id bigint not null,
  name varchar(30),
  sex char(1),
  primary key (id)
);

1.2.1 添加

添加记录的存储过程示例如下

create procedure pro_addStudent (IN id bigint, IN name varchar(30), IN sex char(1))
begin
   insert into student values (id, name, sex);
end

1.2.2 删除

删除记录的存储过程示例如下

create procedure pro_deleteStudent (IN stu_id bigint)
begin
   delete student where id = stu_id;
end

1.2.3 修改

修改记录的存储过程示例如下

create procedure pro_updateStudent (IN stu_id bigint, IN stu_name varchar(30), IN stu_sex char(1))
begin
   update student set name = stu_name, sex = stu_sex where id = stu_id;
end

1.2.4 查询

查询记录的存储过程示例如下

create procedure pro_getStudent (IN stu_id bigint)
begin
   select * from student where id = stu_id;
end

2、在Mybatis中的调用

在mapper.xml文件中调用存储过程如下

<!-- 调用存储过程 -->
<!-- 第一种方式,参数使用parameterType -->
<select id="findStudentById" parameterType="java.lang.Long" statementType="CALLABLE" 
    resultType="com.mybatis.entity.Student">
    {call pro_getStudent(#{id,jdbcType=BIGINT,mode=IN})}
</select>

 <parameterMap type="java.util.Map" id="studentMap">
     <parameter property="id" mode="IN" jdbcType="BIGINT"/>
</parameterMap>

<!-- 调用存储过程 -->
<!-- 第二种方式,参数使用parameterMap -->
<select id="findStudentById" parameterMap="studentMap" statementType="CALLABLE" 
    resultType="com.mybatis.entity.Student">
    {call pro_getStudent(?)}
</select>

版权声明:本文为qq_41883167原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。