MySQL之动态SQL

定义:

动态SQL就是指根据不同的条件生成不同的SQL语句

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

动态SQL之if

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

//如果传入的值为null,或只有title或只有author,会产生不同的结果
<select id="queryBlogIF" parameterType="map" resultType="Blog" resultMap="blog">
    select * from mybatis.blog where 1=1
    <if test="title!=null">
        and title=#{title}
    </if>
    <if test="author!=null">
        and author =#{author}
    </if>
</select>

动态SQL之where

where标签

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

问题:

where后没有条件直接接了[and...]显然是不对的

SELECT * FROM BLOG
WHERE
AND title like ‘someTitle’

这个查询也会失败。这个问题不能简单地用条件元素来解决。这个问题是如此的难以解决,以至于解决过的人不会再想碰到这种问题。

MyBatis 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。而这,只需要一处简单的改动:

<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>
  </where>
</select>

动态SQL之choose

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

<select id="queryBlogIF" parameterType="map" resultType="Blog" resultMap="blog">
    select * from mybatis.blog
    <where>
        <choose>
            <when test="title!=null">
                and title=#{title}
            </when>
            <otherwise>
                and views=#{views}
            </otherwise>
        </choose>
    </where>
</select>

SQL片段

有的时候,我们可能会将一些功能的部分抽取出来,方便复用

1.使用SQL标签抽取公共部分

sql id="if-title-author">
    <if test="title!=null">
        title=#{title},
    </if>
    <if test="author!=null">
        author=#{author},
    </if>
</sql>

2.使用include标签引用

<update id="updateBlog" parameterType="map">
    update mybatis.blog
    <set>
       <include refid="if-title-author"></include>
    </set>
    <where>
        id=#{id}
    </where>
</update>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

莫荒莫慌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值