常用的动态SQL元素:
1、 if 元素: 判断语句,单条件分支判断;
语法:< if test = " 条件"> 满足条件的语句 </if>
<select id="findstu" resultType="Student" parameterType="Student">
select * from student
<where>
<if test="sname != null">
and sname = #{v}
</if>
<if test="sid != 0">
and sid = #{v}
</if>
</where>
</select>
2、choose元素 :
choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则
choose 结束。
当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。
<select id="findStu" parameterType="Sttdent" resultType="Student">
SELECT * FROM STUDENT WHERE SNAME = 'sname'
<choose>
<when test="ssex != null">
AND ssex like #{ssex}
</when>
<when test="birthday != null">
AND birthday like #{birthday }
</when>
<otherwise>
AND sid= 1;
</otherwise>
</choose>
</select>
3、where : 消除 前置 and 或 or
<select id="findstu" parameterType="Student" resultType="Student">
SELECT * FROM Student
<where>
<if test="sname != null">
sname = #{sname}
</if>
<if test="sex != null">
AND sex like #{sex}
</if>
<if test="sid != 0 >
AND sid like #{sid}
</if>
</where>
</select>
4、set :
MyBatis在生成update语句时若使用if标签,如果前面的if没有执行,则可能导致有多余逗号的错误。使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号。 没有使用if标签时,如果有一个参数为null,都会导致错误 ;
set有两个特点:
<update id="xxx" parameterType="xxx">
update 表名
<set>
<if test="属性 != null">
字段名=#{属性},
</if>
<if test="属性 != null">
字段名=#{属性},
</if>
<if test="属性 != null">
字段名=#{属性},
</if>
<if test="属性 != null">
字段名=#{属性},
</if>
</set>
<where> 字段名 = #{属性} </where>
</update>
5、trim :
trim标签是一个万能标签,可以完成set或者是where标记的功能。
四个属性:
(1)prefix:在包含的内容前加上某些前缀;
(2)suffix:在包含的内容后加上某写后缀;
(3)prefixOverrides:把包含内容的首部的某些内容覆盖,即忽略where 和第一个查询条件 之间的and或者是or;
(4)suffixOverrides:把包含内容的尾部的某些内容覆盖。
select * from user
<trim prefix="WHERE" prefixoverride="AND|OR">
<if test="name != null and name.length()>0"> AND name=#{name}</if>
<if test="gender != null and gender.length()>0"> AND gender=#{gender}</if>
</trim>
update user
<trim prefix="set" suffixoverride="," suffix=" where id = #{id} ">
<if test="name != null and name.length()>0"> name=#{name},</if>
<if test="gender != null and gender.length()>0"> gender=#{gender},</if>
</trim>
6、foreach :迭代集合,循环语句;
<select id="findstu" resultType="Student">
SELECT * FROM student WHERE sid
<foreach collection="list" item="list" open=" in (" separator="," close=")">
#{list}
</foreach>
</select>