mybatis调用存储过程

来源:互联网 发布:深圳市在园儿童数据 编辑:程序博客网 时间:2024/04/26 11:02

如何使用Mybaits调用数据库中的存储过程,下面以Oracle数据库的为例:

 

1.在数据库中创建以下的存储过程:

 

    create or replace procedure pro_hello(p_user_name in varchar2,p_result out varchar2) is      begin        p_result := 'hello,' || p_user_name;      end;  


 

2.编写SQL映射文件mapper.xml:

 

    <select id="proHello" statementType="CALLABLE">      <![CDATA[          {call pro_hello (#{p_user_name,mode=IN,jdbcType=VARCHAR},#{result,mode=OUT,jdbcType=VARCHAR})}      ]]>      </select>  


 

3.编写JAVA代码调用存储过程

 

    public class ProcedureTest {                             public static void main(String[] args) throws IOException {                  String resource = "mybatis.cfg.xml";                  Reader reader = Resources.getResourceAsReader(resource);                  SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);                               SqlSession session = ssf.openSession();                              try {                       Map<String, String> param = new HashMap<String, String>();                       param.put("p_user_name", "zhangsan");                       String returnValue = (String) session.selectOne("User.proHello", param);                       System.out.println("message=" + param.get("p_user_name"));                       System.out.println("result=" + param.get("result"));                       System.out.println("returnValue=" + returnValue);                        } catch (Exception e) {                      e.printStackTrace();                 } finally {                    session.close();                }             }      }  


 

4.执行Java代码,控制台输出结果如下:

 

2012-03-07 20:36:32,406 DEBUG [java.sql.PreparedStatement] -==>  Executing: {call pro_hello(?,?)}  2012-03-07 20:36:32,406 DEBUG [java.sql.PreparedStatement] -==> Parameters: zhangsan(String)  message=zhangsan  

0 0