动态SQL
mybatis动态SQL,采用的基于OGNL表达式来操作的。根据表达式的不同进行动态的SQL的拼接、组装
动态SQL标签:if、where、trim标签(where、set)、foreach
1、if标签
if表达式一般使用在SQL的where条件后面,判断参数是否传递使用if test属性,该属性必填,为true或false,test使用的OGNL表达式处理,返回true则进入到if标签中的SQL,返回false则不会进入标签
<select id="selectStudent" parameterType="student" resultMap="StudentMap">
select * from Student where 1=1
<if test="SID != null and SID != 0">
and SID = #{SID}
</if>
<if test="Sage != null">
and Sage = #{Sage}
</if>
</select>
if表达式根据条件包含为where的一部分,常使用与查询,insert操作,update操作
执行情况:
SID和Sage都传递:select * from Student where 1=1 and SID = ? and Sage = ?
SID传递:select * from Student where 1=1 and SID = ?
Sage传递:select * from Student where 1=1 and Sage = ?
不传递参数:select * from Student where 1=1
2、where标签
where标签作用:如果该标签包含的元素有返回值,就插入一个where,如果where后面的字符串是以and或者or开头的,则将他们提出
<select id="selectStudent" parameterType="student" resultMap="StudentMap">
select * from Student
<where>
<if test="SID != null and SID != 0">
and SID = #{SID}
</if>
<if test="Sage != null">
and Sage = #{Sage}
</if>
</where>
</select>
执行情况:
SID和Sage都传递:select * from Student where SID = ? and Sage = ?
SID传递:select * from Student where SID = ?
Sage传递:select * from Student where Sage = ?
不传递参数:select * from Student
where表达式一般和if表达式一块使用,如果条件一个都不满足,则不拼接where条件,如果有一个或者多个if表达式,where会直接拼接在SQL上,并且紧随where的表达式的and或者or会被忽略掉
3、foreach标签
需要根据SID批量的查询Student信息,select * from Student where SID in (1,2,3,4,5);
<select id="selectStudentByIds" resultMap="StudentMap">
select * from Student where SID in
<foreach collection="list" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
标签属性解释:
<foreach表达式>
collection属性:必填,指定的入参的类型;列表:list,数组:array,hashmap:map;
item属性:起名字,给集合中单个元素起名称
open属性:开始的字符串
close属性:结束的字符串
separator属性:数据之间的分隔符