动态sql

If标签:条件判断

test属性:编写ognl表达式

    <select id="queryUsersLikeUserName" resultType="User">
            select * from tb_user where sex = 1
        <if test="userName!=null and userName.trim()!=''">
            and user_name like '%' #{userName} '%'
        </if>
    </select>

choose标签:条件选择

when子标签:用于条件选择,一旦有一个when成立,后续不再执行。
otherwise子标签:所有条件不成立,执行该条件。

<select id="queryUserListByUserNameOrAge" resultType="User">
select * from tb_user where sex = 1
<choose>
    <when test="userName!=null and userName.trim()!=''">
        and user_name like '%' #{userName} '%'
    </when>
    <when test="age!=null">
        and age &lt; #{age}
    </when>
    <otherwise>
        and user_name = 'zhangsan'
    </otherwise>
</choose>
</select>

where标签:用于sql动态条件拼接,添加where关键字,可以将动态sql多余的第一个and或者or去除。

<select id="queryUserListByUserNameAndAge" resultType="User">
        select * from tb_user
        <!-- 
            where标签的作用:
                1、自动添加where关键字
                2、自动去除动态sql前面多余的一个and或者or
         --> 
        <where>
            <if test="userName!=null and userName.trim()!=''">
                and user_name like '%' #{userName} '%'
            </if>
            <if test="age!=null">
                and age = #{age}
            </if>
        </where>
</select>

set标签: 用于更新语句的拼接,添加set关键字,并可以将动态sql中多余的逗号去除

<update id="updateUserSelective" parameterType="User">
        update tb_user
        <set>
            <if test="userName!=null and userName.trim()!=''">
                user_name = #{userName},
            </if>
            <if test="password!=null and password.trim()!=''">
                password = #{password},
            </if>
            <if test="name!=null and name.trim()!=''">
                name = #{name},
            </if>
            <if test="age!=null">
                age = #{age}
            </if>
        </set>
            where id = #{id}
</update>

foreach标签:用于遍历参数中的集合

collection属性:参数中的集合
item属性:表示集合中的某个元素
separator属性:分隔符
open:以什么开始
close:以什么结束

<select id="queryUserListByIds" resultType="User">
        select * from tb_user
        <where>
            <if test="ids!=null">
                <!-- 
                    foreach标签:遍历集合
                        collection属性:接收的集合参数 
                        item属性:集合参数中的每一个元素 
                        separator属性:标签逗号分隔符 
                        open属性:以什么开始 
                        close属性:以什么结束
                 -->
                <foreach collection="ids" item="id" separator="," open="("
                    close=")">
                    #{id}
                </foreach>
            </if>
</where>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值