目录
1、if 标签
<if test="OGNL表达式"> ... </if>
用法比较简单,不做讲解。
2、choose 标签
可以实现 if 。。。else、if。。。else。。。的逻辑,用到了 choose when otherwise 标签。
伪代码:
<choose>
<when test="id != null">
and id = #{id}
</when>
<otherwise>
and 1=2
</otherwise>
</choose>
when标签可以有多个,otherwise标签可以有 0 或 1个。
3、where 标签
当where后面都是if判断后的条件,当所有条件都不成立时只剩下 where造成SQL语法错误;条件部分成立时前缀包括and的情况,造成sql 语法错误。where标签就是为了解决这种尴尬的问题。
where标签的作用:如果该标签包含的元素中有返回值,就插入一个where;如果where后面的字符串是以 AND 和 OR开头的,就将它们剔除。
伪代码:
<where>
<if test="param != null">
and condition = #{param}
</if>
</where>
4、set 标签
set 标签的作用:如果该标签包含的元素中有返回值,就插入一个 set;如果set 后面的字符串是以逗号结尾的,就将这个逗号剔除。
伪代码:
<update id="update">
update table
<set>
<if test="name != null and name != ''">
name = #{name},
</if>
<if...
</set>
</update>
5、trim 标签
where 和 set 标签的功能都可以用 trim 标签来实现,并且在底层就是通过 TrimSqlNode 实现的。
where 标签对应 trim 的实现如下:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
set 标签对应的 trim 实现如下:
<trim prefix="SET" suffixOverrides=",">
...
</trim>
trim 标签有如下属性:
- prefix:当 trim 元素内包含内容时,会给内容增加prefix 指定的前缀。
- prefixOverrides:当trim 元素内包含内容时,会把内容中匹配的前缀字符串去掉。
- suffix:当 trim 元素内包含内容时,会给内容增加suffix指定的前缀。
- suffixOverrides:当trim 元素内包含内容时,会把内容中匹配的后缀字符串去掉。
6、foreach 标签
https://blog.csdn.net/ruanhao1203/article/details/91574817