?
?
如何使用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 |
?