if标签
符合条件就拼接,否则不拼接
<if test="name != null and name != ''">
and NAME = #{name}
</if>
where标签
通常和if联合使用
当标签中第一个符合条件的块的第一个单词是and或者or时,会被自动剔除
<select id="getStudentListWhere" parameterType="Object" resultMap="BaseResultMap">
SELECT * from STUDENT
<where>
<if test="name!=null and name!='' ">
NAME LIKE CONCAT(CONCAT('%', #{name}),'%')
</if>
<if test="hobby!= null and hobby!= '' ">
AND hobby = #{hobby}
</if>
</where>
</select>
choose/when/otherwise标签
类似于java中的switch, 按顺序判断 when 中的条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when
的条件都不满则时,则执行 otherwise 中的 sql。
<select id="getStudentListChoose" parameterType="Student" resultMap="BaseResultMap">
SELECT * from STUDENT WHERE 1=1
<where>
<choose>
<when test="Name!=null and student!='' ">
AND name LIKE CONCAT(CONCAT('%', #{student}),'%')
</when>
<when test="hobby!= null and hobby!= '' ">
AND hobby = #{hobby}
</when>
<otherwise>
AND AGE = 15
</otherwise>
</choose>
</where>
</select>
trim标签
后面多出的and或者or where标签不能解决所以经常会where和trim一起用
prefix=“” 前缀,trim标签体重是整个字符串拼串后的结果
pregix 给拼串后的整个字符串加一个前缀
prefixOverrides="" 前缀覆盖,去掉整个字符串前面多余的字符
suffix =“” 后缀
suffixOverrides ="" 后缀覆盖,去掉整个字符串后面多余的字符
set标签
没有使用 if 标签时,如果有一个参数为 null,都会导致错误。当在 update 语句中使用 if 标签时,如果最后的 if 没有执行,则或导致逗号多余错误。使用 set 标签可以将动态的配置 set关键字,和剔除追加到条件末尾的任何不相关的逗号。
使用 set+if 标签后,如果某项为 null 则不进行更新,而使保持数据库原值。
<update id="updateStudent" parameterType="Object">
UPDATE STUDENT
<set>
<if test="name!=null and name!='' ">
NAME = #{name},
</if>
<if test="hobby!=null and hobby!='' ">
MAJOR = #{major},
</if>
<if test="hobby!=null and hobby!='' ">
HOBBY = #{hobby}
</if>
</set>
WHERE ID = #{id};
</update>
foreach标签
用于处理多条相同的处理语句。具体用法请见 Mybatis中对foreach的处理
collection 指定要遍历的集合
list 类型的参数会特殊处理封装在map中,map的key就叫list
item 将当前遍历出的元素赋值给指定的变量
separator 每个元素之间的分隔符
open 遍历出所有结果拼接一个开始的字符
close 遍历出所有结果拼接一个结束的字符