if
动态 SQL 通常要做的事情是根据条件包含 where 子句的一部分。比如:
<select id="getStudentByConditionIf" resultType="com.Reyco.beans.Student">
select * from student
where score >= #{score}
<if test="name != null">
and name like #{name}
</if>
<if test="age != null">
and age >= #{age}
</if>
</select>
choose,when,otherwise
有时我们不想应用到所有的条件语句,而只想从中择其一项。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句
<select id="getStudentByConditionIf" resultType="com.Reyco.beans.Student">
select * from student
where score >= #{score}
<choose>
<!-- 如果where都不满足,就执行otherwisr,返回所有满足条件的语句-->
<when test="name != null">
and name = #{name}
</when>
<when test="age != null">
and age >= #{age}
</when>
<otherwise>
and 1 = 1
</otherwise>
</choose>
</select>
trim,where,set
实际上前面几个标签已经解决了难搞的动态SQL问题。现在我们尝试将所有的条件都设置为动态的
<select id="getStudentByConditionIf" resultType="com.Reyco.beans.Student">
select * from student
where
<if test="score != null">
score >= #{score}
</if>
<if test="name != null">
and name like #{name}
</if>
<if test="age != null">
and age >= #{age}
</if>
</select>
如果这些条件没有一个能匹配上,最终这条SQL会变成这样
select * from student
where
这会导致查询失败,如果仅仅第二个条件匹配,这条SQL最终会变成这样
select * from student
where
and name like #{name}
这个查询也会失败。
MyBatis 有一个简单的处理,这在 90% 的情况下都会有用。而在不能使用的地方,你可以自定义处理方式来令其正常工作。一处简单的修改就能达到目的:
<select id="getStudentByConditionIf" resultType="com.Reyco.beans.Student">
select * from student
<where>
<if test="score != null">
score >= #{score}
</if>
<if test="name != null">
and name like #{name}
</if>
<if test="age != null">
and age >= #{age}
</if>
</where>
</select>
where元素只会在至少有一个子元素的条件返回SQL子句的情况下才去插入where子句。而且,若语句的开头为“AND”或“OR”,where元素也会将它们去掉。
如果 where 元素没有按正常套路出牌,我们可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<!--trim标签体中是整个字符串拼串后的结果 -->
<!-- prefix给拼串后的字符串加一个前缀-->
<!-- prefixOverrides:前缀覆盖--去掉整个字符串前面多余的字符-->
<!-- suffix给拼串后的字符串加一个后缀-->
<!-- suffixOverrides:后缀覆盖--去掉整个字符串后面多余的字符-->
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
prefixOverrides 属性会忽略通过管道分隔的文本序列(注意此例中的空格也是必要的)。它的作用是移除所有指定在 prefixOverrides 属性中的内容,并且插入 prefix 属性中指定的内容。
类似的用于动态更新语句的解决方案叫做 set。set 元素可以用于动态包含需要更新的列,而舍去其它的。比如:
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>
这里,set 元素会动态前置 SET 关键字,同时也会删掉无关的逗号,因为用了条件语句之后很可能就会在生成的 SQL 语句的后面留下这些逗号
若你对 set 元素等价的自定义 trim 元素的代码感兴趣,那这就是它的真面目:
<trim prefix="SET" suffixOverrides=",">
...
</trim>
注意这里我们删去的是后缀值,同时添加了前缀值
foreach
foreach主要用于构建in条件中,可以在SQL语句中进行迭代集合,元素的属性主要有 item,index,collection,open,separator,close
- item表示集合中每一个元素进行迭代时的别名
- index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置
- open表示该语句以什么开始
- separator表示在每次进行迭代之间以什么符号作为分隔符
- close表示以什么结束
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象传递给 foreach 作为集合参数。当使用可迭代对象或者数组时,index 是当前迭代的次数,item 的值是本次迭代获取的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:
- 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
- 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
- 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可
讲解Collection属性的使用
其实解决collection属性的最好办法就是通过@Param注解为集合起名,collection直接用这个名即可,不需要管什么多参数单参数
内置参数
不只是方法传递过来的参数可以被用来判断和取值,MyBatis默认有两个内置参数
_parameter:代表整个参数
- 单个参数:-parameter就是这个参数
- 多个参数:参数会被封装为一个map,而——parameter就是代表这个map
<!-- List<Employee> getEmpsTestInnerParameter(Employee employee); -->
<select id="getEmpsTestInnerParameter" resultType="com.hand.mybatis.bean.Employee">
SELECT * FROM emp
<!-- _parameter相当于传入的参数employee,判断employee是否为空,若不为空则执行where条件-->
<if test="_parameter!=null">
where ename=#{_parameter.eName}
</if>
</select>
_databaseId:如果配置了databaseIdProvider标签,_databaseId 就是代表当前数据库的别名,可用于多数据库支持。
<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>
bind
bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文。比如
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>