深入浅出Mybatis系列(九)---强大的动态SQL

上篇文章《深入浅出 Mybatis 系列(八)---mapper 映射文件配置之 select、resultMap》简单介绍了 mybatis 的查询,至此,CRUD 都已讲完。本文将介绍 mybatis 强大的动态 SQL。

那么,问题来了: 什么是动态 SQL? 动态 SQL 有什么作用?

  传统的使用 JDBC 的方法,相信大家在组合复杂的的 SQL 语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误。Mybatis 的动态 SQL 功能正是为了解决这种问题, 其通过 if, choose, when, otherwise, trim, where, set, foreach 标签,可组合成非常灵活的 SQL 语句,从而提高开发人员的效率。下面就去感受 Mybatis 动态 SQL 的魅力吧:

 

1. if:    你们能判断,我也能判断!

作为程序猿,谁不懂 if !  在 mybatis 中也能用 if 啦:

<select id="findUserById" resultType="user">
           select * from user where 
           <if test="id != null">
               id=#{id}
           </if>
            and deleteFlag=0;
</select>

上面例子: 如果传入的 id 不为空, 那么才会 SQL 才拼接 id = #{id}。 这个相信大家看一样就能明白,不多说。

细心的人会发现一个问题:“你这不对啊! 要是你传入的 id 为 null,  那么你这最终的 SQL 语句不就成了 select * from user where and deleteFlag=0,  这语句有问题!”

是啊,这时候,mybatis 的 where 标签就该隆重登场啦:

 

2. where, 有了我,SQL 语句拼接条件神马的都是浮云!

咱们通过 where 改造一下上面的例子:

<select id="findUserById" resultType="user">
           select * from user 
<where> <if test="id != null"> id=#{id} </if> and deleteFlag=0; </where> </select>

有些人就要问了: “你这都是些什么玩意儿! 跟上面的相比, 不就是多了个 where 标签嘛! 那这个还会不会出现  select * from user where and deleteFlag=0 ?”

的确,从表面上来看,就是多了个 where 标签而已, 不过实质上, mybatis 是对它做了处理,当它遇到 AND 或者 OR 这些,它知道怎么处理。其实我们可以通过 trim 标签去自定义这种处理规则。

 

3. trim :  我的地盘,我做主!

上面的 where 标签,其实用 trim 可以表示如下:

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

它的意思就是: 当 WHERE 后紧随 AND 或则 OR 的时候,就去除 AND 或者 OR。 除了 WHERE 以外, 其实还有一个比较经典的实现,那就是 SET。

 

4. set:  信我,不出错!

<update id="updateUser" parameterType="com.dy.entity.User">
           update user set 
           <if test="name != null">
               name = #{name},
           </if> 
           <if test="password != null">
               password = #{password},
           </if> 
           <if test="age != null">
               age = #{age}
           </if> 
           <where>
               <if test="id != null">
                   id = #{id}
               </if>
               and deleteFlag = 0;
           </where>
</update>

问题又来了: “如果我只有 name 不为 null,  那么这 SQL 不就成了 update set name = #{name}, where ........ ?  你那 name 后面那逗号会导致出错啊!”

是的,这时候,就可以用 mybatis 为我们提供的 set 标签了。下面是通过 set 标签改造后:

<update id="updateUser" parameterType="com.dy.entity.User">
           update user
<set> <if test="name != null">name = #{name},</if> <if test="password != null">password = #{password},</if> <if test="age != null">age = #{age},</if> </set> <where> <if test="id != null"> id = #{id} </if> and deleteFlag = 0; </where> </update>

这个用 trim 可表示为:

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

WHERE 是使用的 prefixOverrides(前缀), SET 是使用的 suffixOverrides (后缀), 看明白了吧!

 

5. foreach:  你有 for, 我有 foreach, 不要以为就你才屌!

java 中有 for, 可通过 for 循环, 同样, mybatis 中有 foreach, 可通过它实现循环,循环的对象当然主要是 java 容器和数组。

<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 实例或者数组作为参数对象传给 MyBatis,当这么做的时候,MyBatis 会自动将它包装在一个 Map 中并以名称为键。List 实例将会以“list”作为键,而数组实例的键将是“array”。同样, 当循环的对象为 map 的时候,index 其实就是 map 的 key。

 

6. choose:  我选择了你,你选择了我!

Java 中有 switch,  mybatis 有 choose。

<select id="findActiveBlogLike"
     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>

以上例子中: 当 title 和 author 都不为 null 的时候, 那么选择二选一(前者优先), 如果都为 null, 那么就选择 otherwise 中的, 如果 tilte 和 author 只有一个不为 null, 那么就选择不为 null 的那个。

纵观 mybatis 的动态 SQL, 强大而简单, 相信大家简单看一下就能使用了。

好啦,本次就写到这!下篇文章将结合 mybatis 的源码分析一次 sql 语句执行的整个过程。