天天看點

Mybatis調用Oracle中的存儲過程和function

一、mybatis調用存儲過程

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

statementtype裡的callable是标注此sql為存儲過程。

parametertype是标注要傳的參數,看了一些資料不寫parametertype的話預設傳map。還是加上比較清晰

<select id="prohello" parametertype="java.util.map" statementtype="callable">

{call pro_hello(#{uname,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("uname", "zhangsan");

                 param.put("result", "");

                 string returnvalue = (string) session.selectone("user.prohello", param);

                 system.out.println("message=" + param.get("uname"));

                 system.out.println("result=" + param.get("result"));

                 system.out.println("returnvalue=" + returnvalue); 

           } catch (exception e) {

                e.printstacktrace();

           } finally {

              session.close();

          }

       }

}

二、mybatis調用function

function帶有傳回值,假設一個oracle函數增加學生後傳回成功與否的字元串

<select id="ismember" statementtype="callable" parametertype="cn.studentdto">  

{#{result,mode=out,jdbvtype=varchar} = call 

addstudent(#{num,mode=in,jdbctype=decimal},#{name,mode=in,jdbctype=varchar},#{rollinyear,mode=in,jdbctype=date},#{age,mode=out,jdbctype=integer})}  

studentdto除了上述出現的學生資訊字段外還需要string類型的result字段。

原帖位址:

http://chenjc-it.iteye.com/blog/1443432

http://shen84121062.iteye.com/blog/1213857