Mybatis引出的一系列问题-动态 SQL

动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。

if
choose (when, otherwise)
trim (where, set)
foreach

1 if

使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分。比如:

<select id="findActiveBlogWithTitleLike" resultType="Blog">
  SELECT * FROM BLOG
  WHERE state =ACTIVE<if test="title != null">
    AND title like #{
    
    title}
  </if>
</select>

这条语句提供了可选的查找文本功能。如果不传入 “title”,那么所有处于 “ACTIVE” 状态的 BLOG 都会返回;如果传入了 “title” 参数,那么就会对 “title” 一列进行模糊查找并返回对应的 BLOG 结果(细心的读者可能会发现,“title” 的参数值需要包含查找掩码或通配符字符)。

如果希望通过 “title” 和 “author” 两个参数进行可选搜索该怎么办呢?首先,我想先将语句名称修改成更名副其实的名称;接下来,只需要加入另一个条件即可。

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

2 choose、when、otherwise

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句

还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG(这可能是管理员认为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员精选的 Blog)。

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

3 trim、where、set

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

<select id="findActiveBlogLike" 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 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。而这,只需要一处简单的改动:

<select id="findActiveBlogLike" 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 元素也会将它们去除。

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

  <update id="updateBatch" parameterType="java.util.List">
    <!--@mbg.generated-->
    update bs_factory_calendar
    <trim prefix="set" suffixOverrides=",">
      <trim prefix="SET_TIME = case" suffix="end,">
        <foreach collection="list" index="index" item="item">
          when FACTORY_CALENDAR_ID = #{
    
    item.factoryCalendarId,jdbcType=VARCHAR} then #{
    
    item.setTime,jdbcType=VARCHAR}
        </foreach>
      </trim>
      <trim prefix="WEEK = case" suffix="end,">
        <foreach collection="list" index="index" item="item">
          when FACTORY_CALENDAR_ID = #{
    
    item.factoryCalendarId,jdbcType=VARCHAR} then #{
    
    item.week,jdbcType=VARCHAR}
        </foreach>
      </trim>
    </trim>
    where FACTORY_CALENDAR_ID in
    <foreach close=")" collection="list" item="item" open="(" separator=", ">
      #{
    
    item.factoryCalendarId,jdbcType=VARCHAR}
    </foreach>
  </update>

  <insert id="insertOrUpdateSelective" parameterType="com.inspur.spring.pojo.BsFactoryCalendar">
    <!--@mbg.generated-->
    insert into bs_factory_calendar
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="factoryCalendarId != null">
        FACTORY_CALENDAR_ID,
      </if>
      <if test="setTime != null">
        SET_TIME,
      </if>
    </trim>
    values
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="factoryCalendarId != null">
        #{
    
    factoryCalendarId,jdbcType=VARCHAR},
      </if>
      <if test="setTime != null">
        #{
    
    setTime,jdbcType=VARCHAR},
      </if>
    </trim>
    on duplicate key update
    <trim suffixOverrides=",">
      <if test="factoryCalendarId != null">
        FACTORY_CALENDAR_ID = #{
    
    factoryCalendarId,jdbcType=VARCHAR},
      </if>
      <if test="setTime != null">
        SET_TIME = #{
    
    setTime,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>

  <update id="updateByPrimaryKeySelective" parameterType="com.inspur.spring.pojo.BsFactoryCalendar">
    <!--@mbg.generated-->
    update bs_factory_calendar
    <set>
      <if test="updateTime != null">
        UPDATE_TIME = #{
    
    updateTime,jdbcType=TIMESTAMP},
      </if>
      <if test="comId != null">
        COM_ID = #{
    
    comId,jdbcType=VARCHAR},
      </if>
    </set>
    where FACTORY_CALENDAR_ID = #{
    
    factoryCalendarId,jdbcType=VARCHAR}
  </update>

4 foreach

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  <where>
    <foreach item="item" index="index" collection="list"
        open="ID in (" separator="," close=")" nullable="true">
          #{
    
    item}
    </foreach>
  </where>
</select>

猜你喜欢

转载自blog.csdn.net/zs18753479279/article/details/132085784