Ibatis如何调用存储过程?

Ibatis如何调用存储过程?,第1张

存储过程的调用是使用<procedure元素来调用的, 下面是一个使用带输出参数存储过程的例子:

<parameterMap id=swapParameters class=map

�0�2�0�2<parameter property=email1″ jdbcType=VARCHAR javaType=java.lang.String mode=INOUT/

�0�2�0�2<parameter property=email2″ jdbcType=VARCHAR javaType=java.lang.String mode=INOUT/

</parameterMap

如果你的存储过程返回一个结果集,那么使用queryForList()或者queryForObject来调用, 如果你的存储过程既返回结果集又更新数据库数据,那么需要配置<transactionManager的commitRequired=’true’

如果存储过程不返回结果集,或者仅仅以输出参数的形式返回结果集,那么应该使用update()方法。

<procedure id=swapEmailAddresses parameterMap=swapParameters

一.下载最新ibatis包.

二.最新的连接oracle 10g的驱动ojdbc(我这里用的是oracle 10g)

三.下载最新的common包.

示例如下:

函数定义:

Sql代码

CREATE OR REPLACE FUNCTION GetCurTest(

param1invarchar2

param2 invarchar2

)return SYS_REFCURSOR

IS

outCursor SYS_REFCURSOR--输出的游标

BEGIN

open outCursor for

select ORGANCODE from testTable where col1 = GetCurTest.param1 and col2 = GetCurTest.param2

return outCursor

END-- 注意这里用的是SYS_REFCURSOR,在oracle10g里面提供的.

CREATE OR REPLACE FUNCTION GetCurTest(

param1invarchar2

param2 invarchar2

)return SYS_REFCURSOR

IS

outCursor SYS_REFCURSOR--输出的游标

BEGIN

open outCursor for

select ORGANCODE from testTable where col1 = GetCurTest.param1 and col2 = GetCurTest.param2

return outCursor

END-- 注意这里用的是SYS_REFCURSOR,在oracle10g里面提供的.

ibatis中调用如下:

Xml代码

<typeAlias alias="corp" type="com.wes.model.Corp" />

<resultMap id="corp-map" class="corp">

<result property="corpNo" column="ORGANCODE" />

</resultMap>

<parameterMap id="test" class="java.util.HashMap" >

<parameter property="result" jdbcType="ORACLECURSOR" javaType="java.sql.ResultSet" mode="OUT" resultMap="corp-map" />

<parameter property="param1" jdbcType="VARCHAR" javaType="java.lang.String" mode="IN"/>

<parameter property="param2" jdbcType="Date" javaType="java.util.Date" mode="IN"/>

</parameterMap>

<procedure id="testCur" parameterMap="test">

{? = call GetCurTest(?, ?)}

</procedure>

<typeAlias alias="corp" type="com.wes.model.Corp" />

<resultMap id="corp-map" class="corp">

<result property="corpNo" column="ORGANCODE" />

</resultMap>

<parameterMap id="test" class="java.util.HashMap" >

<parameter property="result" jdbcType="ORACLECURSOR" javaType="java.sql.ResultSet" mode="OUT" resultMap="corp-map" />

<parameter property="param1" jdbcType="VARCHAR" javaType="java.lang.String" mode="IN"/>

<parameter property="param2" jdbcType="Date" javaType="java.util.Date" mode="IN"/>

</parameterMap>

<procedure id="testCur" parameterMap="test">

{? = call GetCurTest(?, ?)}

</procedure>

java中调用如下:

Java代码

String resource = "SqlMapConfig.xml"

SqlMapClient client = null

try...{

Reader reader = Resources.getResourceAsReader(resource)

client = SqlMapClientBuilder.buildSqlMapClient(reader)

}catch (Throwable e)...{}

Map p = new HashMap()

p.put("param1","a")

p.put("param2","b")

client.queryForObject(mapid, p)

List list = (List) p.get("result")

if (list == null || list.size() == 0)

list = new ArrayList()

return list

String resource = "SqlMapConfig.xml"

SqlMapClient client = null

try...{

Reader reader = Resources.getResourceAsReader(resource)

client = SqlMapClientBuilder.buildSqlMapClient(reader)

}catch (Throwable e)...{}

Map p = new HashMap()

p.put("param1","a")

p.put("param2","b")

client.queryForObject(mapid, p)

List list = (List) p.get("result")

if (list == null || list.size() == 0)

list = new ArrayList()

return list

list存放的就是我们要的结果集.

4.Procedure

procedure 元素支持存储过程。大部分存储过程要一些类似IN, INOUT 或者 OUT 的参数。所以,创建一个 <parameterMap>元素并列出你要向存储过程传递的参数。只有当参数类型为OUT或者INOUT时parameterMap 对象才会被改变。

Xml代码

<parameterMap id="swapParameters" class="map" >

<parameter property="contactId" jdbcType="INTEGER" javaType="java.lang.Integer" mode="IN"/>

<parameter property="firstName" jdbcType="VARCHAR" javaType="java.lang.String" mode="IN"/>

<parameter property="lastName" jdbcType="VARCHAR" javaType="java.lang.String" mode="IN"/>

</parameterMap>

<procedure id="swapContactName" parameterMap="swapParameters" >

{call swap_contact_name (?, ?,?)}

</procedure>

<parameterMap id="swapParameters" class="map" >

<parameter property="contactId" jdbcType="INTEGER" javaType="java.lang.Integer" mode="IN"/>

<parameter property="firstName" jdbcType="VARCHAR" javaType="java.lang.String" mode="IN"/>

<parameter property="lastName" jdbcType="VARCHAR" javaType="java.lang.String" mode="IN"/>

</parameterMap>

<procedure id="swapContactName" parameterMap="swapParameters" >

{call swap_contact_name (?, ?,?)}

</procedure>

你的代码一开始就要创建一个你要传递给存储过程的参数的 HashMap ,然后把它和你要执行的查询的名称一同传递给 sqlMap 。

Java代码

HashMap paramMap = new HashMap()

paramMap.put("contactId", new Integer(1))

paramMap.put("firstName", "Sunil")

paramMap.put("lastName", "Patil")

sqlMap.queryForObject("swapCustomerName", paramMap)

HashMap paramMap = new HashMap()

paramMap.put("contactId", new Integer(1))

paramMap.put("firstName", "Sunil")

paramMap.put("lastName", "Patil")

sqlMap.queryForObject("swapCustomerName", paramMap)

5.Calling an Oracle procedure function using Ibatis

The ibatis documentation provides a sample on how to call a procedure, but how do you call a function in Oracle? The code sample shows it.

Xml代码

<parameterMap id="getSomeFunction" class="java.util.Map" >

<parameter property="question1" jdbcType="INTEGER" javaType="java.lang.String" mode="OUT"/>

<parameter property="question2" jdbcType="VARCHAR" javaType="java.lang.String" mode="IN"/>

<parameter property="question3" jdbcType="INTEGER" javaType="java.lang.String" mode="IN"/>

<parameter property="question54" jdbcType="VARCHAR" javaType="java.lang.String" mode="IN"/>

<parameter property="question5" jdbcType="VARCHAR" javaType="java.lang.String" mode="IN"/>

</parameterMap>

<procedure id="getSomeFunction" parameterMap="getSomeFunction">

{? = call FNC_EXECUTE_SOME_FUNCTION(?, ?, ?, ?)}

希望能帮到你。

首先定义一个MySQL存储过程:

DROP PROCEDURE IF EXISTS test

CREATE PROCEDURE test (IN p1 VARCHAR(26), OUT pResult VARCHAR(512))

BEGIN

SET pResult := NULL

SET pResult :=CONCAT ( 'test',p1)

SELECT * FROM tb2 WHERE commet like Concat('%',p1, '%')-- this 返回一个结果集

END

tb2的表结构和数据如下:

DROP TABLE IF EXISTS `tb2`

CREATE TABLE `tb2` (

`t_id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主键',

`Name` varchar(255) DEFAULT NULL COMMENT '字段名',

`type` int(1) DEFAULT NULL COMMENT '类型,0-正常,1-异常,2-传输,3-退单',

`commet` varchar(255) DEFAULT NULL COMMENT '备注',

`optime` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT ' *** 作时间',

PRIMARY KEY (`t_id`)

)

继续增加新的类:

Stb2.Java内容:

package com.springdemo.usermgr.vo

import java.util.Date

/**

* tb2表实体类

* @author zhouxj

* @date 2014-09-10 下午03:29:32

*/

public class Stb2{

private Integer t_id

private String name

private Integer type

private String commet

private java.util.Date optime

public Integer getT_id() {

return t_id

}

public void setT_id(Integer t_id) {

this.t_id = t_id

}

public String getName() {

return name

}

public void setName(String name) {

this.name = name

}

public Integer getType() {

return type

}

public void setType(Integer type) {

this.type = type

}

public String getCommet() {

return commet

}

public void setCommet(String commet) {

this.commet = commet

}

public java.util.Date getOptime() {

return optime

}

public void setOptime(java.util.Date optime) {

this.optime = optime

}

}

修改SUserMapper.java内容:

package com.springdemo.usermgr.vo

import java.util.List

import java.util.Map

public interface SUserMapper {

public int insertSUser(SUser user)

public SUser getSUser(String name)

public List<Stb2>getTestProc(Map<String, Object>param)

}

Test2测试类内容:

package domain

import java.io.IOException

import java.io.Reader

import java.util.HashMap

import java.util.List

import java.util.Map

import org.apache.ibatis.io.Resources

import org.apache.ibatis.session.SqlSession

import org.apache.ibatis.session.SqlSessionFactory

import org.apache.ibatis.session.SqlSessionFactoryBuilder

import com.springdemo.usermgr.vo.SUserMapper

import com.springdemo.usermgr.vo.Stb2

public class Test2 {

public static void main(String[] args) throws IOException {

String resource = "config.xml"

Reader reader = Resources.getResourceAsReader(resource)

SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader)

SqlSession session = ssf.openSession(true)//true 为自动提交事务

try {

Map<String, Object>parms = new HashMap<String, Object>()

parms.put("queryStr", "的")

SUserMapper spMapper = session.getMapper(SUserMapper.class)

List<Stb2>as=spMapper.getTestProc(parms)

String outPara=(String) parms.get("retStr")

System.out.println(outPara)

System.out.println(as.toString())

//org.apache.ibatis.type.JdbcType.VARCHAR

// org.apache.ibatis.mapping.ParameterMode.OUT

} catch (Exception e) {

e.printStackTrace()

} finally {

session.close()

}

}

}

config.xml配置文件修改内容:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE configuration PUBLIC

"-//mybatis.org//DTD Config 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

<typeAliases>

<typeAlias alias="SUser" type="com.springdemo.usermgr.vo.SUser" />

<typeAlias alias="Stb2" type="com.springdemo.usermgr.vo.Stb2" />

</typeAliases>

<environments default="development">

<environment id="development">

<transactionManager type="JDBC" />

<dataSource type="POOLED">

<property name="driver" value="com.mysql.jdbc.Driver" />

<property name="url" value="jdbc:mysql://localhost:3306/test"/>

<property name="username" value="root" />

<property name="password" value="pass" />

</dataSource>

</environment>

</environments>

<mappers>

<mapper resource="SUser.xml" />

<mapper resource="Stb2.xml" />

</mappers>

</configuration>

增加配置文件Stb2.xml:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC

"-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.springdemo.usermgr.vo.SUserMapper">

<resultMap type="com.springdemo.usermgr.vo.Stb2" id="itemResult">

</resultMap>

<select id="getTestProc" parameterType="java.util.Map" statementType="CALLABLE"

resultMap="itemResult">

{call test.test(

#{queryStr,jdbcType=VARCHAR,mode=IN},

#{retStr,jdbcType=VARCHAR,mode=OUT})

}

</select>

</mapper>

运行Test2类,可能的结果:

test的

[com.springdemo.usermgr.vo.Stb2@6900bf61, com.springdemo.usermgr.vo.Stb2@3014af22]

返回了参数内容,和两条记录。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5912626.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-08
下一篇 2023-03-08

发表评论

登录后才能评论

评论列表(0条)

保存