Mybatics动态sql

Mybatics动态sql

if语句

只有满足在test中的条件的情况下,才会在查询条件中加入if标签内的内容

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

test中需要包含两个条件的情况下(直接使用and)

<if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>

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>

这里的when相当于case语句,otherwise就相当于switch中的default语句。

trim

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

这种情况下一旦遇到第一个条件不满足,下面某个条件满足就会出现查询条件第一个子条件出现and前缀:如:

SELECT * FROM BLOG
WHERE
AND title like ‘someTitle’

这样的语句很明显会造成程序执行错误。
这时就可以使用trim标签,将上述代码改为:

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE
 **<trim prefix="WHERE" prefixoverride="AND |OR">**
  <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>

prefix:前缀      
prefixoverride:去掉第一个and或者是or
有了这个标签,就很容易解决了子条件出现前缀的问题

foreach

<delete id="deleteBatch"> 
    delete from user where id in
    <foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
      #{id}
    </foreach>
  </delete>

假如 ids = {1,2,3,4,5}
这里的sql就相当于:

delete form user where id in (1,2,3,4,5)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值