英文来自此处
3.9. Dynamic SQL
在ADO里常常遇到的问题就是动态SQL拼接。典型的解决方案是通过if-else语句拼接字符串。iBATIS DataMapper API则提供了一个相对优雅的方式来映射元素。看这个例子:
<select id="dynamicGetAccountList" cacheModel="account-cache" parameterClass="Account" resultMap="account-result" >
select * from ACCOUNT
<isGreaterThan prepend="and" property="Id" compareValue="0">
where ACC_ID = #Id#
</isGreaterThan>
order by ACC_LAST_NAME
</select>
当参数Id > 0的场合,最终的SQL是:
select * from ACCOUNT where ACC_ID = ? order by ACC_LAST_NAME
当参数Id <= 0的场合,最终的SQL是:
select * from ACCOUNT order by ACC_LAST_NAME
以下面这个例子说明一下动态的标签:
<statement id="someName" parameterClass="Account" resultMap="account-result" >
select * from ACCOUNT
<dynamic prepend="where">
<isGreaterThan prepend="and" property="id" compareValue="0">
ACC_ID = #id#
</isGreaterThan>
<isNotNull prepend="and" property="lastName">
ACC_LAST_NAME = #lastName#
</isNotNull>
</dynamic>
order by ACC_LAST_NAME
</statement>
</select>
id | lastName | 结果 |
---|---|---|
1 | null | select * from ACCOUNT where ACC_ID = #id# order by ACC_LAST_NAME |
1 | not null | select * from ACCOUNT where ACC_ID = #id# and ACC_LAST_NAME = #lastName# order by ACC_LAST_NAME (子句的and被where覆盖了) |
0 | null | select * from ACCOUNT order by ACC_LAST_NAME |
0 | not null | select * from ACCOUNT where ACC_LAST_NAME = #lastName# order by ACC_LAST_NAME |
二元标签属性
属性 |
---|
prepend – 直接加到SQL语句中,可被覆盖 (可选项) |
property – 被比较属性 (必须项) |
compareProperty – 要比较的对象(可选项) |
compareValue – 要比较的值 (可选项) |
二元标签
一元标签属性
属性 |
---|
prepend – 直接加到SQL语句中,可被覆盖 (可选项) |
property – 被比较属性 (必须项) |
一元标签
判空标签属性
属性 |
---|
prepend – 直接加到SQL语句中,可被覆盖 (可选项) |
判空标签
迭代标签属性
属性 |
---|
prepend – 直接加到SQL语句中,可被覆盖 (可选项) |
property – 实现了IList接口的可被迭代属性 (必须项) |
open – 开始符,通常是左括号 (可选项) |
close – 结束符,通常是右括号 (可选项) |
conjunction – 迭代结果的连接符, 通常是AND and OR (可选项) |
迭代标签
(注意:不要遗漏#UserNameList[]#里面的方括号)