trim、where、set

前面几个例子已经方便地解决了一个臭名昭著的动态 SQL 问题。现在回到之前的 “if” 示例,这次我们将 “state = ‘ACTIVE’” 设置成动态条件,看看会发生什么。

  1. <select id="findActiveBlogLike"
  2. resultType="Blog">
  3. SELECT * FROM BLOG
  4. WHERE
  5. <if test="state != null">
  6. state = #{state}
  7. </if>
  8. <if test="title != null">
  9. AND title like #{title}
  10. </if>
  11. <if test="author != null and author.name != null">
  12. AND author_name like #{author.name}
  13. </if>
  14. </select>

如果没有匹配的条件会怎么样?最终这条 SQL 会变成这样:

  1. SELECT * FROM BLOG
  2. WHERE

这会导致查询失败。如果匹配的只是第二个条件又会怎样?这条 SQL 会是这样:

  1. SELECT * FROM BLOG
  2. WHERE
  3. AND title like someTitle

这个查询也会失败。这个问题不能简单地用条件元素来解决。这个问题是如此的难以解决,以至于解决过的人不会再想碰到这种问题。

MyBatis 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。而这,只需要一处简单的改动:

  1. <select id="findActiveBlogLike"
  2. resultType="Blog">
  3. SELECT * FROM BLOG
  4. <where>
  5. <if test="state != null">
  6. state = #{state}
  7. </if>
  8. <if test="title != null">
  9. AND title like #{title}
  10. </if>
  11. <if test="author != null and author.name != null">
  12. AND author_name like #{author.name}
  13. </if>
  14. </where>
  15. </select>

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:

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

prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。

用于动态更新语句的类似解决方案叫做 setset 元素可以用于动态包含需要更新的列,忽略其它不更新的列。比如:

  1. <update id="updateAuthorIfNecessary">
  2. update Author
  3. <set>
  4. <if test="username != null">username=#{username},</if>
  5. <if test="password != null">password=#{password},</if>
  6. <if test="email != null">email=#{email},</if>
  7. <if test="bio != null">bio=#{bio}</if>
  8. </set>
  9. where id=#{id}
  10. </update>

这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

来看看与 set 元素等价的自定义 trim 元素吧:

  1. <trim prefix="SET" suffixOverrides=",">
  2. ...
  3. </trim>

注意,我们覆盖了后缀值设置,并且自定义了前缀值。