调用的存储过程
CREATE DEFINER=`root`@`localhost` PROCEDURE `queryStudentName`(IN id char(10), OUT stuname VARCHAR(10))
BEGIN
select sname into stuname from student where sid = id;
end
配置映射文件
<?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="mapper.StudentMapper">
<select id="queryStudentName" statementType="CALLABLE" parameterType="HashMap">
{
CALL queryStudentName(
#{id,jdbcType=VARCHAR,mode=IN},
#{stuname, jdbcType=VARCHAR, mode=OUT}
)
}
</select>
</mapper>
调用存储过程,需要将statementType设置成callable(默认为prepareStatement)
存储过程无论输入参数是什么值,语法上都需要用map来传递该值,然后通过map来获取输出值。
接口文件
public interface StudentMapper {
void queryStudentName(Map<String,Object> params);
}
测试
public class Test {
public static StudentMapper getStudentMapper() throws IOException {
Reader reader = Resources.getResourceAsReader("conf.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sessionFactory.openSession();
return session.getMapper(StudentMapper.class);
}
public static void main(String[] args) throws IOException {
StudentMapper studentMapper = getStudentMapper();
Map<String,Object> params = new HashMap<>();
params.put("id", "8003118001");
studentMapper.queryStudentName(params);
String name = (String) params.get("stuname");
System.out.println(name);
}
}
map中的键的名字与SQL语句中的输入输出参数名相同,通过params.put(“id”, “8003118001”);传入输入参数,OUT值就会自动存储在params中,通过键名stuname就可以获取到值。