【Mybatis】动态sql

转义字符参考网址

https://www.w3cschool.cn/htmltags/ref-entities.html

1. if语句实现条件查询

<!-- 动态sql-->
<select id="getUserByCondition" resultType="com.mj.domain.User">
    select * from User
    <where>
        <if test="id!=null">
            id > #{id}
        </if>
        <if test="username!=null">
            and  username like #{username}
        </if>
        <if test="birthday!=null">
            and  birthday &lt; #{birthday}
        </if>
        <if test="sex!=null">
            and  sex=#{sex}
        </if>
    </where>
</select>

2. 分支查询:choose when

<!--分支查询-->
    <select id="getUserByConditionChoose" resultType="com.mj.domain.User">
        select * from User
        <where>
            <choose>
                <when test="id!=null">
                    id > #{id}
                </when>
                <when test="username!=null  and !username.equals(&quot;&quot;)">
                    username like #{username}
                </when>
                <when test="birthday!=null">
                    birthday &lt; #{birthday}
                </when>
                <when test="sex!=null">
                      sex=#{sex}
                </when>
                <otherwise>
                    1=1
                </otherwise>
            </choose>
        </where>

    </select>

3. foreach 集合遍历

    <select id="getUserByIds" resultType="com.mj.domain.User">
        select * from User where id IN
<!-- 遍历集合-->
<!-- collection:集合的名称
       item:集合中元素的别名,代表的为集合的元素的值value
            index:索引:遍历List时保存指定变量的索引;遍历Map时保存指定变量的Key
       separator:元素之间的分隔符
       open:Sql开始符号
       close:Sql结束符号  -->
        <foreach collection="idlist" item="id_item" separator="," open="(" close=")">
          #{id_item}
        </foreach>
    </select>

4. Update…Set…

<update id="updateUserAuto">
    Update User
    <set>
        <if test="username!=null and !username.equals(&quot;&quot;)">
            username = #{username},
        </if>
        <if test="birthday!=null">
            birthday = #{birthday},
        </if>
        <if test="sex!=null">
            sex = #{sex}
        </if>
    </set>

    <where>
        id = #{id}
    </where>

</update>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值