MyBatis动态sql

官网:mybatis – MyBatis 3 | 动态 SQL

if标签 和 where标签的使用

<select id="findUserByCondition" resultType="domain.User" parameterType="domain.User">
    select * from user
    <where>
        <if test="username != null" >
            and username = #{username}
        </if>
        <if test="sex != null">
            and sex = #{sex}
        </if>
        <if test="birthday != null">
            and birthday = #{birthday}
        </if>
    </where>
​
</select>

foreach标签

<foreach collection="ids" open="and id in (" closs = ")" item = "id" separator=",">
    #{id}
</foreach>
​
<!--
    collection:要遍历的集合元素
    open:开始的片段
    closs:结束的片段
    item:遍历集合的变量
    separator:分割符
-->

choose、when、otherwise

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

        传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG。


trim、where、set

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

        where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <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>
    </set>
  where id=#{id}
</update>

        这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

        或者,你可以通过使用trim元素来达到同样的效果:

<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

抽取sql片段(sql标签)

<!-- 抽取 -->
<sql id="selectUser">select * from testMyBatis.user</sql>
<!-- 使用 -->
<include refid="selectUser"></include>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值