一.概述
MyBatis的最大特性之一便是它的动态SQL。在之前使用JDBC时,我们可以了解到根据不同条件下拼接SQL与许多问题,例如拼接的时候确保不能忘了必要的空格,还要注意省掉列名列表最后的逗号。利用动态SQL这一特性可以彻底摆脱掉这些问题。
通常使用动态SQL不可能是独立的一部分,MyBatis当然使用一种强大的动态SQL语言来改进这种情形,这种语言可以被用在任意的SQL映射语句中。
MyBatis采用功能强大的基于OGNL的表达式来消除其他元素。
二.OGNL表达式
OGNL(Object Graph Navigation Language)对象图导航语言,这是一种强大的表达式语言,通过它可以非常方便的操作对象的属性,类似于EL,SpEL等。
- 访问对象属性:person.name
- 调用方法:person.getName()
- 调用静态属性/方法:@java.lang.Math@PI; @java.util.UUID@randomUUID()
- 调用构造方法:new com.test.bean.Person('admin').name
- 运算符:+,-*,/,%
- 逻辑运算符:in,not in,>,>=,<,<=,==,!=
- 访问集合伪属性:
类型 | 伪属性 | 伪属性对应的 Java 方法 |
List、Set、Map | size、isEmpty | List/Set/Map.size(),List/Set/Map.isEmpty() |
List、Set | iterator | List.iterator()、Set.iterator() |
Map | keys、values | Map.keySet()、Map.values() |
Iterator | next、hasNext | Iterator.next()、Iterator.hasNext() |
注意:xml中特殊符号如>,<等这些都需要转义字符。
三.实验背景
有一个Teacher类:
package com.test.bean;
import java.util.Date;
public class Teacher {
private Integer id;
private String name;
private String course;
private String address;
private Date birth;
@Override
public String toString() {
return "Teacher [id=" + id + ", name=" + name + ", course=" + course
+ ", address=" + address + ", birth=" + birth + "]";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
}
对应的数据库:
四.动态SQL拼接
4.1 if
if 标签通常用于 WHERE 语句、UPDATE 语句、INSERT 语句中,通过判断参数值来决定是否使用某个查询条件、判断是否更新某一个字段、判断是否插入某个字段的值。
<!-- if 判断 -->
<!-- public List<Teacher> getTeacherByCondition(Teacher teacher); -->
<select id="getTeacherByCondition" resultMap="teacherMap">
select * from t_teacher where
<!-- test:编写判断条件
id!=null:取出传入的JavaBean属性中的id的值,判断其是否为空-->
<if test="id!=null">
id >#{id} and
</if>
<!-- name 空串
and: &&-->
<if test="name!=null and name!=''">
tename like #{name}
</if>
</select>
4.2 foreach
foreach 标签主要用于构建 in 条件,可在 sql 中对集合进行迭代。也常用到批量删除、添加等操作中。有以下属性:
- close : 后缀
- open:前缀
- index:索引。如果遍历的是一个list,index指定的变量保存当前遍历的索引,item保存当前元素的值;如果遍历的是一个map,indez指定的变量保存当前遍历元素的key,item保存当前元素的值
- item : 每次遍历出的元素起一个遍历名,方便引用
- separator:每次遍历的元素的分隔符
- collection:collection 属性的值有三个分别是 list、array、map 三种,分别对应的参数类型为:List、数组、map 集合。
<!-- public List<Teacher> getTeacherByInIn(List<Integer> ids); -->
<select id="getTeacherByInIn" resultMap="teacherMap">
select * from t_teacher where id in
<!-- foreach 遍历的集合
collection:指定遍历集合的key-->
<!-- close="" : 以什么结束
index="" :索引,
如果遍历的是一个list:
index指定的变量保存了当前的索引
item保存当前元素的值
如果遍历的是一个map:
index指定的变量就是保存了当前遍历元素的key
item就是保存当前遍历的元素的值
item="" : 每次遍历出的元素起一个遍历名,方便引用
open="" :以什么开始
separator="":每次遍历的元素的分隔符
-->
<foreach collection="ids" item="id_item" separator="," open="(" close=")">
#{id_item}
</foreach>
</select>
4.3 choose:
不想用到所有的条件语句,而只想从中择其一二,针对这种情况,MyBatis提供了choose元素,它有点像Java中的switch语句。
<!-- public List<Teacher> getTeacherByConditionChoose(Teacher teacher); -->
<select id="getTeacherByConditionChoose" resultMap="teacherMap">
select * from t_teacher
<where>
<choose>
<when test="id!=null">
id=#{id}
</when>
<when test="name!=null and !name.equals("")">
tename=#{name}
</when>
<when test="birth!=null">
birthdate=#{birth}
</when>
<otherwise>
1=1
</otherwise>
</choose>
</where>
</select>
只传入id:
五.格式化输出
5.1 where
<!-- if 判断 -->
<!-- public List<Teacher> getTeacherByCondition(Teacher teacher); -->
<select id="getTeacherByCondition" resultMap="teacherMap">
select * from t_teacher where
<if test="id!=null">
id >#{id} and
</if>
<if test="name!=null and name!=''">
tename like #{name}
</if>
</trim>
</select>
执行上面的代码,id不为空且name为空的时候,执行的SQL语句拼接下来是:select * from t_teacher where id=? and。这样的SQL语句执行是由问题的。还可以利用 where标签。这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以 AND 或 OR 开头的,则它会剔除掉。
<!-- if 判断 -->
<!-- public List<Teacher> getTeacherByCondition(Teacher teacher); -->
<select id="getTeacherByCondition" resultMap="teacherMap">
select * from t_teacher
<where>
<if test="id!=null">
id >#{id} and
</if>
<if test="name!=null and name!=''">
tename like #{name}
</if>
</where>
</select>
5.2 trim
trim标记是一个格式化的标记,主要用于拼接sql的条件语句(前缀或后缀的添加或忽略),可以完成set或者是where标记的功能。
trim属性主要有以下四个
- prefix:在trim标签内sql语句加上前缀
- suffix:在trim标签内sql语句加上后缀
- prefixOverrides:指定去除多余的前缀内容,如:prefixOverrides=“AND | OR”,去除trim标签内sql语句多余的前缀"and"或者"or"。
- suffixOverrides:指定去除多余的后缀内容。
<!-- public List<Teacher> getTeacherByCondition(Teacher teacher); -->
<select id="getTeacherByCondition" resultMap="teacherMap">
select * from t_teacher
<!-- 我们的查询条件就放在where,每个and写在前面 where帮我们自动取出前面多余的and -->
<!-- trim 截取字符串
prefix="where" :前缀,为我们下面的所有的SQL整体添加一个前缀
prefixOverrides="" :去除整体字符串多余的字符
suffix="" :为整体添加一个后缀
suffixOverrides="":后面哪个多了可以去掉 -->
<trim prefix="where" suffixOverrides="and" prefixOverrides="and">
<!-- test:编写判断条件
id!=null:取出传入的JavaBean属性中的id的值,判断其是否为空-->
<if test="id!=null">
id >#{id} and
</if>
<!-- name 空串
and: &&-->
<if test="name!=null and name!=''">
tename like #{name}
</if>
</trim>
</select>
5.2 set
没有使用 if 标签时,如果有一个参数为 null,都会导致错误。当在 update 语句中使用 if 标签时,如果最后的 if 没有执行,则或导致逗号多余错误。使用 set 标签可以将动态的配置 set
关键字,和剔除追加到条件末尾的任何不相关的逗号。
<!-- 动态更新 -->
<!-- public int updateTeacher(Teacher teacher); -->
<update id="updateTeacher">
UPDATE t_teacher
<set>
<if test="name!=null and !name.equals("")">
tename=#{name},
</if>
<if test="course!=null and !course.equals("")">
class_name=#{course},
</if>
<if test="address!=null and !address.equals("")">
address=#{address},
</if>
<if test="birth!=null and !birth.equals("")">
birthdate=#{birth}
</if>
</set>
<where>
id=#{id}
</where>
</update>
5.3 bind
<!-- public List<Teacher> getTeacherByCondition(Teacher teacher); -->
<select id="getTeacherByCondition" resultMap="teacherMap">
select * from t_teacher
<trim prefix="where" suffixOverrides="and" prefixOverrides="and">
<if test="id!=null">
id >#{id} and
</if>
<!-- 绑定一个表达式的值到变量 -->
<bind name="_name" value="'%'+name+'%'"/>
<if test="name!=null and name!=''">
tename like #{name}
</if>
</trim>
</select>
include:
<!-- 抽取可重用的SQL -->
<sql id="selectTeacher"> select * from t_teacher</sql>
<!-- public Teacher getTeacherById(Integer id); -->
<select id="getTeacherById" resultMap="teacherMap">
<include refid="selectTeacher"></include>
where id=#id
</select>
三.其它两个参数
3.1_parameter和_databaseId
_parameter:代表传入的参数:
1)传入了单个参数,_parameter就代表这个参数
2)传入了多个参数,_parameter就代表了多个参数集合起来的map
_databaseId:代表当前环境,若在 mybatis 配置文件中配置了 databaseIdProvider , 则可以使用 “_databaseId”变量,这样就可以根据不同的数据库厂商构建特定的语句
mybatis配置文件:
<!-- MyBatis用来考虑数据库移植性 -->
<databaseIdProvider type="DB_VENDOR">
<!-- name:数据库厂商标识
value给这个标识起一个好用的名字
MySQL Oracle -->
<property name="MySQL" value="mysql"/>
<property name="Oracle" value="orcal"/>
</databaseIdProvider>
<insert id="insert">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
<if test="_databaseId == 'oracle'">
select seq_users.nextval from dual
</if>
<if test="_databaseId == 'db2'">
select nextval for seq_users from sysibm.sysdummy1"
</if>
</selectKey>
insert into users values (#{id}, #{name})
</insert>