Mybatis学习笔记[5] 之动态SQL

本文详细介绍了MyBatis框架中动态SQL的使用方法,包括if、where、set及foreach等元素的应用技巧,并通过具体实例展示了如何根据条件动态构建SQL查询和更新语句。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

if & where

动态SQL通常要做的事情就是根据条件包含where子句的一部分

<select id="findUserByUsernameAndSex" 
    parameterType="Demo01.pojo.User" resultType="Demo01.pojo.User">
        select * from `user`
        where 1=1
        <if test="username !=null and username!='' ">
            and username like '%${username}%'
        </if>
        <if test="sex!=null and sex!='' ">
            and sex=#{sex}
        </if>
</select>

可以封装SQL后重用

  • id:这个SQL语句的唯一标识
  • where元素:只会在至少一个子元素的条件返回SQL子句的情况下才会去插入WHERE子句;而且,若语句开头为ANDOR,where元素也会将它们去除
<!-- 封装SQL -->
<sql id="user_Where">
    <where>
        <if test="username != null and uername != '' ">
            and username like '%${username}%'
        </if>
        <if test="sex != null and sex!='' ">
            and sex=#{sex}
        </if>
    </where>
</sql>

<!-- 调用SQL namespace.sql片段 -->
    <select id="findUserByUsernameAndSex" 
        parameterType="Demo01.pojo.User" resultType="Demo01.pojo.User">
        select * from `user`
        <include refid="user_Where"/>
    </select>

set

set元素会动态前置SET关键字,同时也会删除无关的逗号,因为使用条件语句之后很可能就会在生成的SQL语句的后面留下这些逗号

<update id="updateAuthor">
    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>

foreach & 拼接

foreach元素允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它允许你指定开头与结尾的字符串以及在迭代结果之间放置分隔符。当使用可迭代对象或数组时,index是当前的迭代次数,item的值是本次迭代获取的元素,当使用Map对象时候,index是键,item是值。

<!-- 原来的SQL语句 -->
select * from `user` where id in (1,16,28)
<!-- foreach SQL语句 -->
<select id="findUserByIds" parameterType="Demo01.pojo.QueryVo" resultType="Demo01.pojo.User">
    select * from `user`
    <where>
        <if test="ids != null">
            <foreach collection="ids" item="id" open="id in (" close=")" separator=",">
                #{id}           
            </foreach>
        </if>
    </where>
</select>

关键点:

  • foreach:循环传入的集合参数
  • collection:传入的集合名称
  • item:每次循环将循环出的数据放入这个变量中
  • open:循环开始拼接的字符串
  • close:循环结束拼接的字符串
  • separator:循环拼接的分隔符

 

下一篇:Mybatis学习笔记[6] 之关联查询  https://blog.youkuaiyun.com/Rabbit_Judy/article/details/80849369

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值