Mybatis动态SQL映射

动态SQL映射

1.if 结构 test里面的 and 或 or 必须小写

<!-- test里面放判断条件 -->
<if test="id != null and id != -1">
    WHERE id=#{id}
</if>

2.trim-if 多条件结构

<!-- prefix:条件前缀    prefixOverrides:前缀覆盖AND|OR -->
<trim prefix="WHERE" prefixOverrides="AND|OR">
    <if test="id != null">
        AND id=#{id}
    </if>
    <if test="name != null">
        AND userName like CONCAT('%',#{name},'%')
    </if>
</trim> 

3.where-if 多条件结构

<where>
    <if test="id != null">
        AND id=#{id}
    </if>
    <if test="name != null">
        AND userName like CONCAT('%',#{name},'%')
    </if>
</where>

4.choose-when-otherwise 多选一结构

<choose>
    <when test="id!=null">
        WHERE id=#{id}
    </when>
    <when test="name!=null">
        WHERE userName like CONCAT('%',#{name},'%')
    </when>
    <otherwise>
        <!-- 上面条件都不满足时执行 -->
    </otherwise>
</choose>

5.foreach 循环结构 代替 WHERE id IN (?,?..)

    WHERE id IN
<!-- collection:集合名称 item:每一个元素 open:sql开始部位 separator:中间分隔符 close:sql结束部位 -->
<foreach collection="ids" item="id" open="(" separator=","
    close=")">
    #{id}
</foreach>

6. set-if 或 trim-if 修 改数据结构

<update id="setUser">
    UPDATE smbms_user
    <set>
        <if test="userCode != null and userCode != ''">userCode = #{userCode} , </if>
        <if test="userName != null">userName = #{userName}, </if>
    </set>
    WHERE id = #{id}
    <!-- 或 -->
    <!-- prefix:前缀  suffixOverrides:修改的后缀覆盖  suffix:后缀 -->
    <trim prefix="SET" suffixOverrides="," suffix="WHERE id = #{id}">
        <if test="userCode != null">userCode = #{userCode} , </if>
        <if test="userName != null">userName = #{userName}, </if>
    </trim>
</update>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

LOVE_DDZ

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

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

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

打赏作者

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

抵扣说明:

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

余额充值