一、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})}  

</select>

StudentDTO除了上述出现的学生信息字段外还需要String类型的result字段。



原帖地址:

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

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