Mybatis技术(五)Mybatis调用存储过程

如何使用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();  
          }  
       }  
} 

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

  1. 2016-04-24 20:36:32,406 DEBUG [java.sql.PreparedStatement] -==>  Executing: {call pro_hello(?,?)}  
  2. 2016-03-24 20:36:32,406 DEBUG [java.sql.PreparedStatement] -==> Parameters: zhangsan(String)  
  3. message=zhangsan 

你可能感兴趣的:(Mybatis技术(五)Mybatis调用存储过程)