1.MyBatis动态SQL简介

  1. 动态 SQL是MyBatis强大特性之一。极大的简化我们拼装SQL的操作

  2. 动态 SQL 元素和使用 JSTL 或其他类似基于 XML 的文本处理器相似

  3. MyBatis 采用功能强大的基于 OGNL 的表达式来简化操作

if

choose (when, otherwise)

trim (where, set)

foreach

  1. OGNL( Object Graph Navigation Language )对象图导航语言,这是一种强大的

表达式语言,通过它可以非常方便的来操作对象属性。 类似于我们的EL,SpEL等

访问对象属性: person.name

调用方法: person.getName()

调用静态属性/方法: @java.lang.Math@PI

​ @java.util.UUID@randomUUID()

调用构造方法: new com.atguigu.bean.Person(‘admin’).name

运算符: +,-*,/,%

逻辑运算符: in,not in,>,>=,<,<=,==,!=

注意:xml中特殊符号如 ” , > , < 等这些都需要使用转义字符

if where

  1. if用于完成简单的判断.

  2. where用于解决SQL语句中where关键字以及条件前面的and或者or的问题

注:可以用and ‘’ 代替转义字符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<select id="getEmployeeByConditionIf" resultType="com.atguigu.mybatis.entities.Employee">
select id,last_name,email,salary
from employees
<where>
<if test="id!=null">
id=#{id}
</if>
<if test="lastName!=null&amp;&amp;lastName!=&quot;&quot;">
and last_name=#{lastName}
</if>
<if test="email!=null and email.trim()!=''">
and email=#{email}
</if>
<if test="salary!=null">
and salary=#{salary}
</if>
</where>
</select>

set

  1. set 主要是用于解决修改操作中SQL语句中可能多出逗号的问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<update id="updateEmployeeByConditionSet">
update employees
<set>
<if test="lastName!=null and lastName.trim()!=''">
last_name = #{lastName},
</if>
<if test="email!=null and email.trim()!=''">
email = #{email},
</if>
<if test="salary!=null">
salary = #{salary},
</if>
</set>
where id = #{id}
</update>