• MyBatis调用Oracle的存储过程


    一、传入与输出都是单值参数

    存储过程定义:

    create or replace procedure pro_test1(param1 in number, param2 in number, param3 out number) 
    is
    begin
    param3:=param1+param2;
    end pro_test1;

    DAO

    void testProcedure2(Map<String, Object> map);

    MyBatis 

    <select id="testProcedure2" statementType="CALLABLE">
        {call pro_test1(#{v_p1, mode=IN, jdbcType=INTEGER}, #{v_p2, mode=IN, jdbcType=INTEGER}, #{v_p3, mode=OUT,jdbcType=INTEGER})}
    </select>

    注意这里的 mode=IN, jdbcType=INTEGER ,两个属性是必须的,且值要大写否则会出错。jdbcType与数据库数据类型的对应关系在文末有链接。

    测试

    
        @Test
        public void test2(){
            Map<String, Object> map = new HashMap<>();
            map.put("v_p1", 1);
            map.put("v_p2", 2);
            bookCategoryDao.testProcedure2(map);
            System.out.println(map);
    
        }
    //输出-----

      {v_p3=3, v_p2=2, v_p1=1}
      class java.lang.Integer

    
    

    调用存储过程的参数要放在Map中,入参指定好key、value,出参不用指定,在MyBatis的mapper文件中 #{v_p3, mode=OUT,jdbcType=INTEGER}   v_p3会作为出参的key放入Map中,值为存储过程返回值。

    二、输出结果集

    存储过程定义:

    create or replace procedure pre_test(v_cursor out sys_refcursor) 
    is
    begin
      open v_cursor for select * from t_book_category;
    end pre_test;

    sys_refcursor 是用于返回结果集的游标

    DAO

    void testProcedure1(Map<String, Object> map);

    MyBatis

    <resultMap id="hMap" type="java.util.HashMap">
      <id column="book_category_id" property="id"/>
      <result column="book_category_name" property="name"/>
    </resultMap>
    
    <select id="testProcedure1" statementType="CALLABLE">
        {call pre_test(#{result, mode=OUT, jdbcType=CURSOR, javaType=ResultSet, resultMap=hMap})}
    </select>

    javaType=ResultSet ,resultMap=hMap两个参数是返回结果集必须的
    如果没有javaType=ResultSet会引起类型转换异常:

      java.lang.ClassCastException: oracle.jdbc.driver.OracleResultSetImpl cannot be cast to java.util.List

    resultMap=hMap 指定结果集的每条的封装规则;每一条就是数据表的一条记录,除了用Map接收还能用指定pojo对象接收。

    测试

    @Test
    public void test1(){
        Map<String, Object> map = new HashMap<>();
        bookCategoryDao.testProcedure1(map);
        Object o = map.get("result");
        System.out.println(o);
        System.out.println(o.getClass());
        List l = (List) o;
        System.out.println(l.get(0).getClass());
    }

    输出

    附一个MyBatis的jdbcType与Oracle、MySql的数据类型对应关系:https://www.cnblogs.com/yadongliang/p/7739303.html

  • 相关阅读:
    JDK环境变量配置
    Leetcode 645. 错误的集合
    map、vector内存释放
    Leetcode 605. 种花问题(终于解决)
    QT自定义QTABLEWIDGET
    Qtcreator调试源码
    Eclipse安装教程
    C/C++常用工具库
    pandas目录
    Lesson3——Pandas Series结构
  • 原文地址:https://www.cnblogs.com/liuyiyuan/p/12944414.html
Copyright © 2020-2023  润新知