六、Mybatis-动态SQL

动态SQl

1.if 标签

  <select id="xx" resultType="xxx">
        select * from user where 1=1
        <if test="name != null and name !=''">
            and name = #{name}
        </if>
        <if test="age != null and age != ''">
            and age = #{age}
        </if>


    </select>

2. where标签

 <select id="xxx">
        select * from user
    <where>
        <if test="name != null and name !=''">
            and name = #{name}
        </if>
        <if test="age != null and age != ''">
            and age = #{age}
        </if>
    </where>
    </select>

where会把 多余的 and,or,自动去掉。当where标签内没有内容时,就不会显示where

3.trim标签

  • prefix/suffix 将trim标签内的内容,前面/后面添加指定内容

  • prefixOverrides/suffixOverrides 将trim标签中内容前面或后面 去掉指定内容

  • 若标签中没有内容时,trim标签也没有任何效果

 <select id="xxxx">

    <!---
      prefix/suffix 将trim标签内的内容,前面/后面添加指定内容
      prefixOverrides/suffixOverrides 将trim标签中内容前面或后面 去掉指定内容
      若标签中没有内容时,trim标签也没有任何效果
    -->
        <trim prefix="where"   suffixOverrides="and | or">
            <if test="name != null and name !=''">
                and name = #{name}
            </if>
            <if test="age != null and age != ''">
                and age = #{age}
            </if>

        </trim>
    </select>

4.choose when otherwise 标签

choose when otherwise 相当于 if…else…if…else

所以 when 和 otherwise 只有一个条件执行

    <select id="xxxx">
        select * from user 
        <where>
            <choose>
                <when test="name != null and name != ''">
                    name = #{name}
                </when>
                
                <when test="age != null and age != null">
                    age = #{age}
                </when>

                <otherwise>
                    eid =1
                </otherwise>
            </choose>
        </where>
    </select>

5.foreach 标签

批量删除

  <delete id="xxxx">
        delete from user where id in(
            <foreach collection="ids" item="id" separator=",">
                #{id}
            </foreach>
            )
    </delete>

或者

 <delete id="xxxx">
        delete from user where id in
            <foreach collection="ids" item="id" separator="," open="(" close=")">
                #{id}
            </foreach>
            
    </delete>

或者

 <delete id="xxxx">
        delete from user where 
            <foreach collection="ids" item="id" separator="or" >
               id= #{id}
            </foreach>

</delete>

批量添加

<insert id="">
        insert into user values
        <foreach collection="emps" item="emp" separator=",">
            (null,#{emp.name},#{emp.sex},#{emp.age})
        </foreach>
    </insert>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值