动态 SQL 语法

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

我们以 User 表为例来说明:

if 语句

说明

if元素是简单的条件判断逻辑,满足指定条件时追加if元素内的SQL

语法结构

<select ... >
  SQL语句
  <if test="条件表达式">
     追加的 sql 语句
  </if>
</select>

示例代码

根据 username 和 sex 来查询数据。如果username为空,那么将只根据sex来查询;反之只根据username来查询:

<select id="selectUserByUsernameAndSex" resultType="user" parameterType="user">
    select * from user where
        <if test="username != null">
           username=#{username}
        </if>
        <if test="username != null">
           and sex=#{sex}
        </if>
</select>

注意:这样写我们可以看到,如果 sex 等于 null,那么查询语句为 select from user where username=#{username}并没问题,但是如果usename 为空呢?那么查询语句为 select from user where and sex=#{sex},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句

where+if 语句

说明

where元素主要是用于简化查询语句中where部分的条件判断。where元素可以在<where>元素所在的位置输出一个where关键字,而且还可以将后面的条件多余的and或or关键字去掉。

语法结构

<select..>
   select 字段 from 表
   <where>
    <if test="条件表达式1">
        追加的 sql 语句1
    </if>
    <if test="条件表达式2">
        追加的 sql 语句2
    </if>
    ...
   </where>
</select>

示例代码

解决上诉 if 带来的SQL 语句错误的问题,可以选择使用 wehre+if 语句来解决:

<select id="selectUserByUsernameAndSex" resultType="user" parameterType="user">
    select * from user
    <where>
        <if test="username != null">
           username=#{username}
        </if>
        <if test="username != null">
           and sex=#{sex}
        </if>
    </where>
</select>

问:上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,我们怎么处理呢?

set+if 语句

说明

​ set元素主要是用在更新操作的时候,它的主要功能和where元素相似,主要是在set元素所在位置输出一个set关键字,而且还可以去除内容结尾中无关的逗号。

语法结构

<update...>
    update 表
    <set>
       动态追加更新字段
       <if test="条件判断"></if>
       <if test="条件判断"></if>
       <if test="条件判断"></if>
       ...
    </set>
    ...
</update>

示例代码

根据 id 更新 user 表的数据:

<update id="updateUserById" parameterType="user">
    update user u
        <set>
            <if test="username != null and username != ''">
                u.username = #{username},
            </if>
            <if test="sex != null and sex != ''">
                u.sex = #{sex}
            </if>
        </set>
     where id=#{id}
</update>

这样写

  • 如果第一个条件 username 为空,那么 sql 语句为:update user u set u.sex=? where id=?
  • 如果第一个条件username不为空,第二个条件 sex 为空,那么 sql 语句为:update user u set u.username = ? where id=?

会自动去掉结尾多余的 逗号。

choose(when,otherwise) 语句

有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题。

说明

choose元素的作用相当于JAVA中的Switch语句,一般和otherwist搭配使用。

语法结构

<select..>
SQL语句1
 <choose>
   <when test="条件表达式1">
       条件1满足追加的 sql 
   </when>
   <when test="条件表达式2">
       条件2满足追加的 sql 
   </when>
   <otherwise>
       否则追加的 sql 语句
   </otherwise>
 </choose>
</select>

示例代码

<select id="selectUserByChoose" resultType="user" parameterType="user">
      select * from user
      <where>
          <choose>
              <when test="id !='' and id != null">
                  id=#{id}
              </when>
              <when test="username !='' and username != null">
                  and username=#{username}
              </when>
              <otherwise>
                  and sex=#{sex}
              </otherwise>
          </choose>
      </where>
  </select>

也就是说这里我们有三个条件,id,username,sex,只能选择一个作为查询条件

  • 如果 id 不为空,那么查询语句为:select * from user where id=?
  • 如果 id 为空,那么看username 是否为空,如果不为空,那么语句为 select * from user where username=?;
  • 如果 id 为空,username 也为空,那么查询语句为 select * from user where sex=?

trim 语句

说明

可以在自己包含的内容前加上某前缀,也可以在其后加上某些后缀,对应的属性分别是prefix和suffix;
可以把包含内容的首部某些内容过滤,即忽略,也可以把尾部的某些内容过滤,对应的属性分别是prxfixOverrides和suffixOverridex;
正因为trim有上述功能,所有我们也可以非常简单的利用trim来代替where和set元素的功能。

语法结构

<!-- 等价于where元素 -->
<trim prefix="WHERE" prefixOverrides="AND|OR">
 ...
</trim>
<!--等价于set元素-->
<trim prefix="SET" prefixOverrides=",">
 ...
</trim>

示例代码

<!--根据 username 和 sex 来查询数据。如果username为空,那么将只根据sex来查询;反之只根据username来查询-->
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="user">
        select * from user
        <trim prefix="where" prefixOverrides="and|or">
            <if test="username != null">
               and username=#{username}
            </if>
            <if test="sex != null">
               and sex=#{sex}
            </if>
        </trim>
</select>
  • prefix:添加前缀 where
  • prefixoverride:去掉第一个and或者是or
<!-- 根据 id 更新 user 表的数据 -->
    <update id="updateUserById" parameterType="com.ys.po.User">
        update user u
            <trim prefix="set" suffixOverrides="," suffix="where">
                <if test="username != null and username != ''">
                    u.username = #{username},
                </if>
                <if test="sex != null and sex != ''">
                    u.sex = #{sex},
                </if>
            </trim>
          id=#{id}
    </update>

prefix:添加前缀 set

suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)

suffix:添加后缀 where

foreach

说明

foreach元素实现了逻辑循环,可以进行一个集合的迭代,主要用在构建in条件中。

语法结构

<select ...>
    select * from 表 where 字段 in**
    <foreach collection="集合" index="索引" item="迭代变量" open="(" separator=","close=")">
    </foreach>
</select>

示例代码

需要查询 user 表中 id 分别为1,2,3的用户:

sql语句:

  • select * from user where id=1 or id=2 or id=3
  • select * from user where id in (1,2,3)

用 foreach 来改写 select * from user where id=1 or id=2 or id=3

<select id="selectUserByListId" parameterType="int" resultType="user">
    select * from user
    <where>
        <!--
            collection:指定输入对象中的集合属性
            item:每次遍历生成的对象
            open:开始遍历时的拼接字符串
            close:结束时拼接的字符串
            separator:遍历对象之间需要拼接的字符串
            select * from user where 1=1 and (id=1 or id=2 or id=3)
          -->
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id=#{id}
        </foreach>
    </where>
</select>

用 foreach 来改写 select * from user where id in (1,2,3)

<select id="selectUserByListId" parameterType="com.ys.vo.UserVo" resultType="com.ys.po.User">
        select * from user
        <where>
            <!--
                collection:指定输入对象中的集合属性
                item:每次遍历生成的对象
                open:开始遍历时的拼接字符串
                close:结束时拼接的字符串
                separator:遍历对象之间需要拼接的字符串
                select * from user where 1=1 and id in (1,2,3)
              -->
            <foreach collection="ids" item="id" open="and id in (" close=") " separator=",">
                #{id}
            </foreach>
        </where>
    </select>

SQL 片段

有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。

比如:假如我们需要经常根据用户名和性别来进行联合查询,那么我们就把这个代码抽取出来,如下:

<!-- 定义 sql 片段 -->
<sql id="selectUserByUserNameAndSexSQL">
    <if test="username != null and username != ''">
        AND username = #{username}
    </if>
    <if test="sex != null and sex != ''">
        AND sex = #{sex}
    </if>
</sql>

引用 sql 片段

<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
    select * from user
    <trim prefix="where" prefixOverrides="and|or">
        <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
        <include refid="selectUserByUserNameAndSexSQL"></include>
        <!-- 在这里还可以引用其他的 sql 片段 -->
    </trim>
</select>

注意:

  1. 最好基于单表来定义 sql 片段,提高片段的可重用性
  2. 在 sql 片段中不要包括 where

总结

其实动态 sql 语句的编写往往就是一个拼接的问题,为了保证拼接准确,我们最好首先要写原生的 sql 语句出来,然后在通过 mybatis 动态sql 对照着改,防止出错。

results matching ""

    No results matching ""