第八章 动态SQL
2020-04-08 本文已影响0人
Y_Jaaao
动态SQL中的元素介绍
动态SQL有什么作用
- MyBatis提供了对SQL语句动态组装的功能
动态SQL中的元素

if元素
-
<if>元素是最常用的判断语句,主要用于实现某些简单的条件选择
示例
choose-when-otherwise元素


<where>元素
- 在映射文件中编写的SQL后面都加入“where 1=1”的条件。如果将“1=1”去掉,则会出现SQL语句语法错误。如下:
加入条件“1=1”后,既保证了where后面的条件成立,又避免了where后第一个词是and/or等关键词
<where>
<trim>元素
-
通过trim标签,动态构建where条件(prefix="where")
<trim>
prefixOverrides 属性
- 通过prefixOverrides="and" 去掉动态构建where条件的第一个and。
- 会忽略通过管道分隔的文本序列(注意此例中的空格也是必要的)。
- 作用是移除所有指定在 prefixOverrides 属性中的内容,并且插入 prefix 属性中指定的内容。
<set>元素
-
主要作用:用于更新操作,在动态包含的SQL语句前输出一个SET关键字,并将SQL语句中最后一个逗号去除
示例
<foreach>元素

<foreach>主要属性

<foreach>中collection属性的注意事项

<bind>元素
-
<bind>元素可以通过OGNL表达式创建一个上下文变量,方法如下:
示例