Mybatis 的动态 SQL 语句

if

if 就是__简单的条件判断 __,利用if语句我们可以实现某些简单的条件选择。
先来看如下一个例子:

<select id="selectUserByUserNameAndSex" resultType="com.george.pojo.User" parameterType="com.george.pojo.User">
    select * from user where
        <if test="userName != null">
           username=#{userName}
        </if>
         
        <if test="userName != null">
           and sex=#{sex}
        </if>
</select>

  

在JDBC中如果要实现条件查询,采用的是拼串的方式,而且sql语句往往和java代码混杂在一起,非常麻烦。

choose(when,otherwise)

choose元素的作用就相当于JAVA中的switch语句,基本上跟JSTL中的choose的作用和用法是一样的,通常都是与when和otherwise搭配的。看如下一个例子:

<select id="selectUserByChoose" resultType="com.george.pojo.User" parameterType="com.george.pojo.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>

  

when元素表示当when中的 条件满足的时候就输出其中的内容 ,只有一个会输出 ,当title!=null的时候就输出and titlte = #{title},不再往下判断条件,当title为空且content!=null的时候就输出and content = #{content},当所有条件都不满足的时候就输出otherwise中的内容。

where

where语句的作用主要是 简化SQL语句中where中的条件判断 ,先看一个例子,再解释一下where的好处。

<select id="selectUserByUserNameAndSex" resultType="com.george.pojo.User" parameterType="com.george.pojo.User">
    select * from user
    <where>
        <if test="userName != null">
           username=#{userName}
        </if>
         
        <if test="userName != null">
           and sex=#{sex}
        </if>
    </where>
</select>

(1)会在写入where元素的地方输出一个where
(2)如果所有的条件都不满足那么MyBatis就会查出所有的记录
(3)如果输出后是and 开头的,MyBatis会把第一个and忽略,当然如果是or开头的,MyBatis也会把它忽略
(4)在where元素中你不需要考虑空格的问题,MyBatis会智能的帮你加上

trim

<insert id="addBrand" parameterType="Brand">
    insert into bbs_brand
    <trim prefix="(" suffix=")">
     name,
     description,
     img_url,
     sort,
     is_display
    </trim>
    values
    <trim prefix="(" suffix=")">
     #{name},
     #{description},
     #{imgUrl},
     #{sort},
     #{isDisplay}
    </trim>
</insert>

trim元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix.
可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;

set

set元素主要是用 在更新操作的时候在包含的语句前输出一个set 。
有了set元素我们就可以动态的更新那些修改了的字段。下面是一段示例代码:

<update id="updateUserById" parameterType="com.george.pojo.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>

(1)如果包含的语句是以逗号结束的话将会把该逗号忽略
(2)如果set包含的内容为空的话则会出错

foreach

foreach的主要用在 构建in条件中 ,它可以在SQL语句中进行迭代一个集合 。

foreach元素的属性主要有:

  • item表示集合中每一个元素进行迭代时的别名
  • index指定一个名字,用于表示在迭代过程中,每次迭代到的位置
  • open表示该语句以什么开始
  • separator表示在每次进行迭代之间以什么符号作为分隔符
  • close表示以什么结束
  • collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:

(1)果传入的是单参数且参数类型是一个List的时候,collection属性值为list

<select id="dynamicForeachTest" resultType="Blog">
  select * from t_blog where id in
  <foreach collection="list" index="index" item="item" open="(" separator="," close=")" >
    #{item}
  </foreach>
</select>
public List<Blog> dynamicForeachTest(List<Integer> ids);

(2)如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array

<select id="dynamicForeach2Test" resultType="Blog">
  select * from t_blog where id in
  <foreach collection="array" index="index" item="item" open="(" separator="," close=")" >
    #{item}
  </foreach>
</select>
public List<Blog> dynamicForeach2Test(int[] ids);

(3)如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key

<select id="dynamicForeach3Test" resultType="Blog">
  select * from t_blog where title like "%"#{title}"%" and id in
  <foreach collection="ids" index="index" item="item" open="(" separator="," close=")" >
      #{item}
  </foreach>
</select>
public List<Blog> dynamicForeach3Test(Map<String, Object> params);

(4)foreach标签遍历的集合元素类型是Map.Entry类型时,index属性指定的变量代表对应的Map.Entry的key,item属性指定的变量代表对应的Map.Entry的value。此时如果对应的集合是Map.entrySet,则对应的collection属性用collection。foreach在进行遍历的时候如果传入的参数是List类型,则其collection属性的值可以是list或collection,但如果传入的参数是Set类型,则collection属性的值只能用collection。

<select id="dynamicForeach2Test" resultType="Blog">
  select * from t_blog where id in
  <!-- 遍历的对象是Map.Entity时,index代表对应的Key,item代表对应的value   -->
  <foreach collection="collection" index="key" item="value" open="(" separator="," close=")" >
      #{key},#{value}
  </foreach>
</select>

  

public List<Blog> dynamicForeachTest(Set<Map.Entry<Integer, Integer>> ids);

bind

bind标签,动态SQL中已经包含了这样一个新的标签,它的功能是在当前OGNL上下文中创建一个变量并绑定一个值。
有了它以后我们以前的模糊查询就可以改成这个样子:

<select id="fuzzyQuery" resultType="Blog" parameterType="java.lang.String">
 <!-- bind标签用于创建新的变量   -->
  <bind name="titleLike" value="'%' + _parameter + '%'" />
  SELECT * FROM t_blog
  WHERE title LIKE #{titleLike}
</select>
原文地址:https://www.cnblogs.com/yscec/p/12044209.html