iBatis中获取存储过程输出参数
存储过程定义如下:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE sp_InsertRequisition
@ID bigint output,
@ProposerID int,
@Available bit,
@Priority varchar(10),
@Stage varchar(50)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [Procurment].[dbo].[Requisition]
([ProposerID]
,[Available]
,[Stage]
,[Priority])
VALUES
(@ProposerID,@Available,@Stage,@Priority)
SELECT @ID = IDENT_CURRENT('Requisition')
END
GO
配置文件定义如下:
<?xml version="1.0" encoding="UTF-8" ?>
<sqlMap namespace="Requisition"
xmlns="http://ibatis.apache.org/mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<statements>
<insert id="InsertRequisitionParameterMap" parameterClass="Requisition">
INSERT INTO [Procurment].[dbo].[Requisition]
([ProposerID]
,[Available]
,[Stage]
,[Priority])
VALUES
(#ProposerID#,#Available#,#Stage#,#Priority#)
<selectKey resultClass="Int64" type="post" property="Id" >
select @@IDENTITY as value
</selectKey>
</insert>
<procedure id="sp_InsertRequisition" parameterMap="insert-parameter">
sp_InsertRequisition
</procedure>
</statements>
<parameterMaps>
<parameterMap id="insert-parameter" class="Requisition">
<parameter property="Id" direction="Output" dbType="bigint" column="ID"/>
<parameter property="ProposerID"/>
<parameter property="Available" dbType="bit"/>
<parameter property="Priority"/>
<parameter property="Stage"/>
</parameterMap>
</parameterMaps>
</sqlMap>
可以使用SQL语句,然后指定<selectKey resultClass="Int64" type="post" property="Id" >
select @@IDENTITY as value
</selectKey>来取得当前主键的值,也可以执行SP后获取输出参数
指定存储过程时重要的一步是一定要把输出参数的名称对应到实体的相应属性中才可以。iBatis会把实体属性值做为ref类型进行相应的修改(在MappedStatement类中有RetrieveOutputParameters方法)
程序代码如下调用:
public void Insert(Requisition requisition)
{
this.ExecuteInsert("sp_InsertRequisition", requisition);
}
父类中定义:
protected object ExecuteInsert(string statementName, object parameterObject)
{
try
{
ISqlMapper sqlMap = this.GetMapper();
return sqlMap.Insert(statementName, parameterObject);
}
catch (Exception ex)
{
throw new DataAccessException("Error executing ExecuteInsert. Cause :" + ex.Message, ex);
}
}