动态SQL语句

本文详细介绍了MyBatis中的动态SQL元素,包括If标签用于条件判断,Where标签智能处理where关键字,Set标签处理update语句中的逗号,以及Foreach标签用于方便地构建in查询。此外,还提到了Choose-when-otherwise结构,它类似Java的switch语句,用于条件选择。
摘要由CSDN通过智能技术生成

一、If标签
If标签通常不单独使用,与where或set一起使用

二、Where标签
Where标签自动生成where关键字,在遇到第一个字段是AND或OR时,会做自动去除的处理。

<select id="selectUsers" resultType="Sysuser" parameterType="Sysuser">
        select * from sysuser
        <where>
          <if test="uid!=null">
              and uid=#{uid}
          </if>
          <if test="uname!=null and uname!=''">
              and uname=#{uname}
          </if>
          <if test="uphone!=null and uphone!=''">
              and uphone=#{uphone}
          </if>
            <if test="upwd!=null and upwd!=''">
                and upwd=#{upwd}
            </if>
            <if test="uemail!=null and uemail!=''">
                and uemail=#{uemail}
            </if>
        </where>
        order by update_time desc
    </select>

三、Set标签、
Set标签用在update标签中,来完成修改SQL语句中的逗号去除。

<update id="updateUserByIdSelective" parameterType="sysuser">
      update sysuser
       <set>
           <if test="uname!=null">
               uname=#{uname},
           </if>
           <if test="uphone!=null and uphone!=''">
                uphone=#{uphone},
           </if>
           <if test="upwd!=null and upwd!=''">
                upwd=#{upwd},
           </if>
           <if test="uemail!=null and uemail!=''">
                uemail=#{uemail},
           </if>
       </set>
       where uid=#{uid}
    </update>

四、Foreach标签
当需要使用in函数查询时,可以使用foreach语句来拼接字符串
collection – 传递参数类型list/array
index – 循环索引
item – 集合中的元素
open –以什么开始; close – 以什么结束

<insert id="addUsers">
        insert into sysuser(uname,upwd,uphone,uemail,rid) values
        <foreach collection="array" separator="," item="suser">
            (#{suser.uname},#{suser.upwd},#{suser.uphone},#{suser.uemail},#{suser.rid})
        </foreach>
    </insert>

五、Choose-when-otherwise
Mybatis中的choose标签相当于Java中的switch。

<select id="selectUsersOneCondition" resultType="Sysuser" parameterType="Sysuser">
        select * from sysuser
        <where>
            <choose>
                <when test="uid!=null">
                    uid=#{uid}
                </when>
                <when test="uname!=null and uname!=''">
                    uname=#{uname}
                </when>
                <when test="uphone!=null and uphone!=''">
                    uphone=#{uphone}
                </when>
                <otherwise></otherwise>
            </choose>
        </where>
        order by update_time desc
    </select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值