MyBatis动态sql语句

1、if

        if元素可以用于根据条件判断是否包含某个SQL语句片段。

<!--
    查询年龄大于18岁且小于等于30岁的用户信息:
    <if>元素用于判断minAge和maxAge是否为null,
    如果不为null,则将对应的SQL语句片段拼接到最终的SQL语句中
-->
<select id="findUsersByAge" parameterType="Map" resultType="User">
    SELECT *
    from user
    WHERE 1 = 1
    <if test="minAge != null">
        AND age &gt;= #{minAge}
    </if>
    <if test="maxAge != null">
        AND age &lt;= #{maxAge}
    </if>
</select>

2、where元素

        where元素可以用于动态生成where子句,如果所有条件均为null,则不会生成where子句

<!--
    查询用户名和密码匹配的用户信息:
    <where>元素用于动态生成where子句,
    如果username和password均为null,则不会生成where子句
-->
<select id="findUserByUsernameAndPassword" parameterType="Map" resultType="User">
    SELECT *
    FROM user
    <where>
        <if test="username != null">
            AND username = #{username}
        </if>
        <if test="password != null">
            AND password = #{password}
        </if>
    </where>
</select>

3、foreach

        foreach元素可以用于循环遍历一个集合,并将集合中的元素拼接到SQL语句中。

<!-- 
    查询多个用户信息:
    <foreach>元素用于循环遍历List类型的参数,并将集合中的元素拼接到SQL语句中
-->
<select id="findUsersByIds" parameterType="List" resultType="User">
    SELECT *
    FROM user
    WHERE id IN
    <foreach collection="list" item="id" open="(" separator="," close=")">
        #{id}
    </foreach>
</select>

4、choose(when、otherwise)

        choose 相当于 java 里面的 switch 语句。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>

5、trim

        prefix:前缀prefixoverride:去掉第一个and或者是or

select * from test
<trim prefix="WHERE" prefixoverride="AND丨OR">
      <if test="a!=null and a!=' '">AND a=#{a}<if>
      <if test="b!=null and b!=' '">AND a=#{a}<if>
</trim>

6、set

        set 元素主要是用在更新操作的时候,如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。

<update id="dynamicSetTest" parameterType="Blog">  
    update t_blog  
    <set>  
        <if test="title != null">  
            title = #{title},  
        </if>  
        <if test="content != null">  
            content = #{content},  
        </if>  
        <if test="owner != null">  
            owner = #{owner}  
        </if>  
    </set>  
    where id = #{id}  
</update> 

  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

清爽的暗之妖刀0369

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

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

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

打赏作者

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

抵扣说明:

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

余额充值