iBatis笔记
有些老项目在使用iBatis,所以也学习了下,记录下学习笔记。
标签
dynamic
标签
内容来自ibatis的dynamicSQL中,关于prepend的使用
当需要使用根据传入参数的值来动态组装SQL时,可以使用dynamic
标签。
<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>
dynamic元素可以包含多个条件比较元素,并且按照条件比较元素的表述对参数值进行比较,来组装动态SQL。
这里主要的条件比较元素包含isGreaterThan
、isNotNull
、isEmpty
……
dynamic元素和条件比较元素,都是组成动态SQL的一部分,其中的prepend属性根据实际情况的需要辅助的组装动态SQL。
以上面的statement为例:
1)dynamic的prepend
只要检测到第一个为“真”的条件比较元素,则覆盖其prepend属性并组装where关键字为动态SQL的一部分。
2)isNotNull
的prepend
只要检测到参数值满足比较条件,则前置组装and关键字为动态SQL的一部分。
在iBATIS中
isNull
用于判断参数是否为Null
,isNotNull
相反
isEmpty
判断参数是否为Null或者空,满足其中一个条件则其true
isNotEmpty
相反,当参数既不为Null
也不为空是其为true
参考ibatis 中isNull, isNotNull与isEmpty, isNotEmpty区别
iterator用法
内容来自iBatis动态条件查询
Person
代码大致如下:
public class Person{
public Person(int age){
this.age=age;
}
/**
* 年龄
*/
private int age;
/**
* 性别
*/
private String sex;
//get/set方法略
...
}//end of Person
PersonDaoImp
如下:
/**
* 删除性别为man,年龄为 11,12 的Person记录
*/
public int deletePerson(Map<String, Object> map) {
List<Person> personList=new ArrayList<Person>();
Person p1=new Person(11);
person p2=new Person(12);
personList.add(p1);
personList.add(p2);
map.put("personList", personList);
map.put("sex",'man');
return getSqlMapClientTemplate().delete(
"person.deletePerson", map);
}
person.xml
如下:
<!-- 删除相应的person记录 -->
<delete id="deletePerson" parameterClass="map">
delete from 表名 where sex=#sex#
<iterate prepend="and" property="personList" open="("
close=")" conjunction="or">
age=$personList[].age$
</iterate>
</delete>
输出sql如下:
delete from 表名 where sex='man' and (age =11 or age=12)
当然你也可以这么写:
person.xml
如下:
delete from 表名 where sex=#sex# and age in
<iterate property="personList" open="("
close=")" conjunction=",">
$personList[].age$
</iterate>
</delete>
输出sql如下:
delete from 表名 where sex='man' and age in (11 ,12)
注意的问题
1.iBATIS中$与#的区别
参考: