本章节将介绍 MyBatis 怎样调用带有 IN 类型参数的 MySQL 存储过程。
(1)定义存储过程 proc_updateUserName,该存储过程将根据 userId 修改用户名称 userName。SQL脚本如下:
CREATE PROCEDURE `proc_updateUserName`(IN `userId` int,IN `userName` varchar(100)) BEGIN update `user` set `name`=userName where user_id=userId; END
(2)MyBatis 配置 mybatis-cfg.xml 文件内容如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="database.properties"/> <environments default="MySqlDatabase" > <environment id="MySqlDatabase" > <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/hxstrive/mybatis/procedure/demo1/UserMapper.xml" /> </mappers> </configuration>
(3)定义 Mapper 接口,UserMapper.java 代码如下:
package com.hxstrive.mybatis.procedure.demo1; import org.apache.ibatis.annotations.Param; public interface UserMapper { /** * 更新用户名称 * @param userId * @param userName */ void updateUserName(@Param("userId") int userId, @Param("userName") String userName); }
(4)编写Mapper XML文件,代码如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hxstrive.mybatis.procedure.demo1.UserMapper"> <!-- 调用存储过程 --> <update id="updateUserName"> {call proc_updateUserName(#{userId}, #{userName})} </update> </mapper>
注意:调用存储过程的语法和 JDBC一致,即 {call 存储过程名称}
(5)编写客户端,代码如下:
package com.hxstrive.mybatis.procedure.demo1; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; public class ProcedureDemo { public static void main(String[] args) throws Exception { String cfgName = "com/hxstrive/mybatis/procedure/demo1/mybatis-cfg.xml"; InputStream input = Resources.getResourceAsStream(cfgName); SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlFactory = factoryBuilder.build(input); SqlSession sqlSession = sqlFactory.openSession(true); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.updateUserName(1, "Tom"); } }
执行成功后,自行查看数据库记录是否被修改。