iBatis.Net系列(五) ParameterMap
来源:WEB开发资源联盟(http://cnpoint.com/)
作者:point
原文:iBatis.Net系列(五) ParameterMap(http://cnpoint.com/net/2006/0907/content_675.htm)
iBatis.Net系列(五) ParameterMapDonald 发表于 2006-5-27 17:05:17
在用Ado.Net进行数据库访问操作中,最麻烦的就是准备DbCommand必须为它添加DbParameter,特别是当要传的参数特别多的情况下,数据访问层的很多代码都是花在这里。iBatis的ParameterMap配置就是针对这个问题所提出的一种解决方案,基于xml的配置,把字段名和对象的属性对应起来,通过运行时的一些工作,自动为DbCommand提供它所需的参数集合。从而避免了我们直接写很多重复代码。
在Employees_ParameterMap.xml配置文件中:
<selectid="Employees_SelectWithParameterClass"parameterClass="Employee"resultClass="Employee"listClass="ArrayList">
select EmployeeID,LastName,FirstName from Employees where EmployeeID = #EmployeeID# or LastName = #LastName#
</select>
使用的是内联参数映射的方式,语句的在执行查询时只需为它提供Employee类型的对象,它就会自动去读自己需要的EmployeeID,LastName属性的值,返回查询结果。在执行时它所执行的语句如下:
[select EmployeeID,LastName,FirstName from Employees where EmployeeID = @param0 or LastName = @param1]
所需的参数的提供方式如下:
[@param0=[EmployeeID,12], @param1=[LastName,8bbb7bfb-c]]
并且,在iBatis中还会指出各个参数的类型:
[@param0=[Int32, System.Int32], @param1=[String, System.String]]
对于下面这个配置:
<selectid="Employees_SelectWithParameterMap1"parameterMap="Employee_SelectParameterMap"resultClass="Employee"listClass="ArrayList">
select EmployeeID,LastName,FirstName from Employees where EmployeeID = #EmployeeID# or LastName = #LastName# or Country = #Country#
</select>
它所使用的ParameterMap配置如下:
<parameterMapclass="Employee"id="Employee_SelectParameterMap">
<parametercolumn="EmployeeID"property="EmployeeID"dbType="int"type="int"direction="Input"/>
<parametercolumn="LastName"property="LastName"dbType="nvarchar"type="string"direction="Input"/>
<parametercolumn="Country"property="Country"dbType="nvarchar"type="string"direction="Input"/>
</parameterMap>
在每一个Parameter映射元素可以指定每个属性对应的列,它的类型和对应的数据库的类型,还可以指定当它为空值时的默认值,具体可以参看官方文档。但是可以看到,我们期待它能和内联参数一样的使用方法,如上配置的那样。可是行不行呢?从程序的执行结果来看,是不可以的。由于之前在配置SQL语句的时候基本都是使用内联参数没有特别注意到这点。在使用Parameter Map的时候是不能用#property#的形式显示地指定要使用的属性参数,只能通过“?”,顺序替代每一个parameter元素,如下:
<selectid="Employees_SelectWithParameterMap2"parameterMap="Employee_SelectParameterMap"resultClass="Employee"listClass="ArrayList">
select EmployeeID,LastName,FirstName from Employees where EmployeeID = ? or LastName = ? or Country = ?
</select>
可以看到,由于没有明显地指出EmployeeID对应哪个属性,那如果把上面的parameter元素调换一下,那么EmployeeID所对应的参数值就发生变化了。同时,也是这个原因,通过这种方式的参数映射,就无法重复利用每个参数了。如果仔细观察会发现,既然都指定了column属性了,那它为什么不会自动去配置呢?其实在这边column属性是不起作用的,它只会作用在执行存储过程的时候。也就是说上面的Parameter元素中的column属性不是必须的。下面是一个存储过程的例子:
<procedureid="Employee_InsertWithProcedure"parameterMap="Employee_InsertParameterMap2"resultClass="int">
InsertEmployee
</procedure>
InsertEmployee接受两个参数@LastName和@FirstName。我给它提供的映射参数如下:
<parameterMapclass="Employee"id="Employee_InsertParameterMap2">
<parametercolumn="LastName"property="LastName"dbType="nvarchar"type="string"direction="Input"/>
<parametercolumn="FirstNam
[1] [2] 下一页
进入问吧