通过上一篇文章,大概了解了Ibatisnet中SqlMap的配置,但仅仅有SqlMap我们还不能进行IBatisnet的操作,我们还需要根据数据库表来编写映射文件.
Ibatisnet的xml映射文件主要包括这几个部分,resultMaps,parameterMaps,下面分别说一下IBatisnet的映射文件中的Elements及其Attributes.
一、Statements
简单的说,这一部分里放的是对数据库操作的SQL语句及存储过程等,它包括以下子元素:
Statement Element | Attributes | Child Elements | Methods |
---|---|---|---|
<statement> |
id |
All dynamic elements |
Insert |
<insert> |
id |
All dynamic elements |
Insert |
<update> |
id |
All dynamic elements |
Insert |
<delete> |
id |
All dynamic elements |
Insert |
<select> |
id |
All dynamic elements |
All query methods |
<procedure> |
id |
All dynamic elements |
Insert |
然后说一下,这些Statement Element的Attributes
1、id
statement的标识,每个statement必须的attribute,还需注意的是,在所有的sqlmap中,它都是唯一的。
2、parameterMap
parameterMap的值会按照顺序匹配statement中的sql语句中的?(占位符)。如下:
<parameterMap id="simpleinsert" class="Employees">
<parameter property="id"/>
<parameter property="empcode"/>
</parameterMap>
</parameterMaps>
<statement id="insertEmployee" parameterMap="simpleinsert">
insert into Employees (Id, EmpCode) values (?,?);
</statement>
上面代码中的parameterMap中我们定义了两个参数id,empcode,而在下面的statement中的insert语句的第一个?就
会被id的值所取代,第二个?的值为empcode的值。当然IBatisnet中并不是这样一种参数的定义方式,另外还有两种inline,named
方式。
3、parameterClass
还是看上面的例子,如果我们没有对statement指定parameterMap,我们还可以通过指定parameterClass并使用inline parameter来完成同样的目的。如下:
insert into Employees (Id, EmpCode) values (#Id#,#EmpCode#);
</statement>
parameterClass也可以直接写成Employees。
insert into Employees (Id, EmpCode) values (#Id#,#EmpCode#);
</statement>
4、resultMap
通过设置resultMap,我们可以控制如何从查询的结果集中提取数据。比如我们只需要结果集中的某几列就可以来设置resultMap中的result来完成。
<resultMap id="SelectResult" class="Employees">
<result property="Id" column="id" />
<result property="EmpCode" column="empcode" />
<result property="EmpPassword" column="emppassword" />
<result property="EmpName" column="empname" />
<result property="EmpSex" column="empsex" />
<result property="EmpAge" column="empage" />
<result property="EmpMail" column="empmail" />
<result property="EmpPhoneNo" column="empphoneno" />
<result property="Description" column="description" />
<result property="IsAdmin" column="isadmin" />
<result property="IsDelete" column="isdelete" />
</resultMap>
</resultMaps>
select * from Employees
</statement>
上面这个statement的查询结果就返回Employees的所有列,如果你只想返回其中几列,只需要更改resultMap就可以了。
5、resultClass
对于控制查询结果的返回值,我们也可以通过设置resultClass来代替resultMap。指定的resultClass将自动对应到查询结果的列。
Select
id as Id,
empcode as EmpCode,
emppassword as EmpPassword,
empname as EmpName,
empsex as EmpSex,
empage as EmpAge,
empmail as EmpMail,
empphoneno as EmpPhoneNo,
description as Description,
isadmin as IsAdmin,
isdelete as IsDelete
From Employees
</select>
Employees.cs应包括Id,EmpCode,EmpPassword,EmpName,EmpSex,EmpAge,EmpMail,EmpPhoneNo,Description,IsAdmin,IsDelete这些属性。