Mybatis---动态SQL(if、choose、trim、foreach)

6 篇文章 0 订阅

一、if标签

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

<select id="findActiveBlogLike"
     resultType="Blog">
     <!-- WHERE与if标签之间尽量加一个条件例如del_flag=0或1=1 -->
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <!-- test:判断表达式(OGNL)
  		ognl会进行字符串与数字的转换判断  "0"==0
        遇见特殊符号应该去写转义字符:&&、''等字符
        -->
  <if test="title != null">
  <!-- AND写在前面,写在后面的话较为奇怪(需要在最后if标签后加1=1) -->
    AND title like #{title}
  </if>
  <if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>
</select>

二、choose、when、otherwise标签

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

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

三、trim标签

可以用于等价替代where标签set标签
也是上面if标签提到,如果没有where后会没有条件的时候使用

  • 参数
属性描述
prefix给sql语句拼接的前缀
suffix给sql语句拼接的后缀
prefixOverrides去除sql语句前面的关键字或者字符,该关键字或者字符由prefixOverrides属性指定,假设该属性指定为"AND",当sql语句的开头为"AND",trim标签将会去除该"AND"
suffixOverrides去除sql语句后面的关键字或者字符,该关键字或者字符由suffixOverrides属性指定
  • 替代where
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  <trim prefix="WHERE" prefixOverrides="AND">
    <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>
  </trim>
</select>
  • 替代set(去除多余的逗号)
<update id="updateAuthorIfNecessary">
  update Author
    <trim prefix="SET" suffixOverrides=",">
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </trim>
  where id=#{id}
</update>

三、foreach标签

foreach标签用于对集合进行遍历(尤其是在构建 IN 条件语句的时候)

属性描述
collection参数名称,根据Mapper接口的参数名确定,也可以使用@Param注解指定参数名
item参数调用名称,通过此属性来获取集合单项的值
open相当于prefix,即在循环前添加前缀
close相当于suffix,即在循环后添加后缀
index索引、下标
separator分隔符,每次循环完成后添加此分隔符
<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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值