---
title: "MyBatis动态SQL"
author: "xdwangiflytek"
date: "2012-12-18T19:02:14Z"
tags: ["MyBatis", "Set", "foreach", "trim", "动态sql"]
categories: ["企业架构"]
slug: "mybatis-sql"
draft: false
lastmod: "2012-12-20T14:24:12Z"
id: 1749938
url: "https://xdwangiflytek.iteye.com/blog/1749938"
---

MyBatis 另一个强大功能特性是它的动态 SQL 能力，如果你有使用 JDBC 或者其他相似框架的经验，你就明白根据条件串联 SQL 字符串在一起是多么的痛苦，需要确保不能忘记空格、最后省略号、顿号等等。而 MyBatis 动态 SQL 可以解决这种问题。

         通常使用动态 SQL 不可能是独立的一部分， MyBatis 当然使用一种强大的动态 SQL 语言来改进这种情况，这种语言可以被用在任意映射的 SQL 语句中。

动态 SQL 元素和使用 JSTL 或其他相似的基于 XML 的文本处理器相似。在 MyBatis 之前的版本中 , 有很多的元素需要来了解。 MyBatis 3 大大提升了它们 , 现在用不到原先一半的元素就能工作了。 MyBatis 采用功能强大的基于 OGNL 的表达式来消除其他元素。

·         if

·         choose (when, otherwise)

·         trim (where, set)

·         foreach

**If**

         If 在动态 SQL 中所做的最通用的事情是包含部分 where 子句的条件，比如：

```
<select id="findActiveBlogLike" 
     parameterType="Blog" resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’ 
  <if test="title != null">
    AND title like #{title}
  </if>
  <if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>
</select>
```

 

**choose, when, otherwise**

有时我们不想应用所有的条件 , 相反我们想选择很多情况下的一种。 Java 中的 switch 和语句相似 ,MyBatis 提供 choose 元素

```
<select id="findActiveBlogLike" 
     parameterType="Blog" resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>
```

 

 

**trim, where, set**

```
<select id="findActiveBlogLike" 
     parameterType="Blog" resultType="Blog">
  SELECT * FROM BLOG 
  WHERE 
  <if test="state != null">
    state = #{state}
  </if> 
  <if test="title != null">
    AND title like #{title}
  </if>
  <if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>
</select>
```

 

如果这些条件都没有匹配上将会发生什么 ? 这条 SQL 结束时就会成这样 :

SELECT * FROM BLOG

WHERE

这会导致查询失败。如果仅仅第二个条件匹配是什么样的 ? 这条 SQL 结束时就会是这样 :

SELECT * FROM BLOG

WHERE

AND title like ‘someTitle’

MyBatis 提供了一个处理方式，即 where

```
<select id="findActiveBlogLike" 
     parameterType="Blog" resultType="Blog">
  SELECT * FROM BLOG 
  <where> 
    <if test="state != null">
         state = #{state}
    </if> 
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
  </where>
</select>
```

 

where 元素知道如果由被包含的标记返回任意内容 , 就仅仅插入“ WHERE ”。而且 , 如果以“ AND ”或“ OR ”开头的内容 , 那么就会跳过 WHERE 不插入。

其实这个我们在 JDBC 拼接 SQL 时还有一种处理方式：

```
<select id="findActiveBlogLike" 
     parameterType="Blog" resultType="Blog">
  SELECT * FROM BLOG 
  WHERE 
  <if test="state != null">
    state = #{state}
  </if> 
  <if test="title != null">
    AND title like #{title}
  </if>
  <if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>
</select>
```

 如果 where 元素没有做出你想要的,你可以使用 trim 元素来自定义。如下:

```
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ... 
</trim>
```

 

trim 元素的主要功能是可以在自己包含的内容前加上某些前缀，也可以在其后加上某些后缀，与之对应的属性是 prefix 和 suffix ；可以把包含内容的首部某些内容覆盖，即忽略，也可以把尾部的某些内容覆盖，对应的属性是 prefixOverrides 和 suffixOverrides ；正因为 trim 有这样的功能，所以我们也可以非常简单的利用 trim 来代替 where 元素的功能。

prefix ：前缀覆盖并增加其内容；

suffix ：后缀覆盖并增加其内容；

prefixOverrides ：前缀判断的条件；

suffixOverrides ：后缀判断的条件；

 

和动态更新语句相似的解决方案是 set 。 set 元素可以被用于动态包含更新的列 , 而不包 含不需更新的。比如 :

```
<update id="updateAuthorIfNecessary"
       parameterType="domain.blog.Author">
  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 关键字 , 而且也会消除任意无关的逗号 , 那也许在应用条件之后来跟踪定义的值。

如果这里也使用 trim ，则为：

```
<trim prefix="SET" suffixOverrides=",">
  ...
</trim>
```

 

注意这种情况下我们覆盖一个后缀 , 而同时也附加前缀。

 

**foreach**

另外一个动态 SQL 通用的必要操作是迭代一个集合 , 通常是构建在 IN 条件中的。 比如

```
<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>
```

 

foreach 元素是非常强大的 , 它允许你指定一个集合 , 声明集合项和索引变量 , 它们可 以用在元素体内。它也允许你指定开放和关闭的字符串 , 在迭代之间放置分隔符。这个元素 是很智能的 , 它不会偶然地附加多余的分隔符。

item表示集合中每一个元素进行迭代时的别名， index指定一个名字，用于表示在迭代过程中，每次迭代到的位置，open表示该语句以什么开始，separator表示在每次进行迭代之间以什么符号作为分隔符，close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性，该属性是必须指定的，但是在不同情况下，该属性的值是不一样的，主要有一下3种情况：  
1.如果传入的是一个参数且参数类型是一个List的时候，collection属性值为list  
2.如果传入的是一个参数且参数类型是一个array数组的时候，collection的属性值为array  
3.如果传入的参数是多个的时候，我们就需要把它们封装成一个Map了，当然单参数也可以封装成map，实际上如果你在传入参数的时候，在breast里面也是会把它封装成一个Map的，map的key就是参数名，所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key  
单参数List的类型：

```
  <select id="dynamicForeachTest" resultType="Blog"> 
        select * from t_blog where id in 
        <foreachcollection="list" index="index" item="item" open="(" separator="," close=")">
             #{item} 
        </foreach> 
    </select> 
```

 

```
public List<Blog> dynamicForeachTest(List<Integer> ids); 
```

 单参数Array的类型

```
  <select id="dynamicForeach2Test" resultType="Blog"> 
        select * from t_blog where id in 
        <foreachcollection="array" index="index" item="item" open="(" separator="," close=")">
             #{item} 
        </foreach> 
    </select> 
```

 public List&lt;Blog&gt; dynamicForeach2Test(int\[] ids);

 

自己把参数封装成Map的类型

```
<select id="dynamicForeach3Test" resultType="Blog"> 
        select * from t_blog where title like "%"#{title}"%" and id in 
        <foreachcollection="ids" index="index" item="item" open="(" separator="," close=")">
             #{item} 
        </foreach> 
    </select> 
```

 上述collection的值为ids，是传入的参数Map的key，对应的Mapper代码：

```
public List<Blog> dynamicForeach3Test(Map<String, Object> params);
```

 

```
 public void testMap() { 
			SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
			try {
				   BlogMapper blogMapper = session.getMapper(BlogMapper.class); 
			        final List<Integer> ids = new ArrayList<Integer>(); 
			        ids.add(1); 
			        ids.add(2); 
			        Map<String, Object> params = new HashMap<String, Object>(); 
			        params.put("ids", ids); 
			        params.put("title", "中国"); 
			        List<Blog> blogs = blogMapper.dynamicForeach3Test(params); 
			        for (Blog blog : blogs) 
			            System.out.println(blog); 
				sqlSession.commit();
			} finally {
				sqlSession.close();
			}
	    } 
```

 

 

再多说一点， MyBatis 中动态 SQL 中使用 &gt; 、 &lt; 等符号时，需要用 []()[&lt;!\[CDATA\[]()    …  ]]&gt; 括起来。

比如说判断时间范围时：

```
<if test="queryBeginDate != null and queryBeginDate!=''" >		<![CDATA[
		and c.createdate >= #{queryBeginDate,jdbcType=NVARCHAR}
	]]>
</if>
```