SQL语句的动态拼接(2)

mapper.xml

<!--
       set作用:  会自动增加set关键字,并且会去除最后一个逗号
            只可以使用修改
    -->
    <update id="update">
          update   flower
        <set>
              <if test="name!=null and  name!=''">
                  name =#{name},
              </if>
              <if test="production!=null and production!=''">
                  production=#{production},
              </if>
               id =#{id}
        </set>
         where
          id =#{id}
    </update>
    <!--
        prefix:增加前缀
        prefixOverrides:去除前缀
        suffix:增加后缀
        suffixOverrides:去除后缀
    -->
    <update id="update2">
        update   flower
          <trim prefix="set"   suffixOverrides=",">
                <if test="name!=null and  name!=''">
                    name =#{name},
                </if>
                <if test="production!=null and production!=''">
                    production=#{production},
                </if>
          </trim>
        where
        id =#{id}
    </update>

    <!--
        collection: list/array
        open:开始
        close:关闭
        separator:分割
        item:赋值给指定属性
    -->
    <select id="selectMore5"  resultType="flower">
        SELECT  <include refid="sq1"></include> FROM   flower  WHERE  id  in
        <foreach collection="list" open="("  separator="," close=")" item="ii">
             #{ii}
        </foreach>
    </select>

    <select id="selectMore6" resultType="flower">
      SELECT  <include refid="sq1"></include>   from  flower
      <where>

            <if test="param1!=null and  param1!=''">
                 <!--模糊查询拼接-->
                 <bind name="pa" value="'%'+param1+'%'"></bind>
                name like   #{pa}
            </if>
          <if test="param2!=null and  param2!=''">
             and  production =#{param2}
          </if>
      </where>
    </select>
    <!--公共sql片段-->
   <sql id="sq1">
     id,name,price,production
   </sql>

MyBatis中动态拼接标签小结:

if :类似于if()只要满足条件就可以拼接

where:增加where关键字  去除第一个and --查询

choose:类似if(){}else if(){},只会进入符合条件的第一个

set:会自动增加set关键字 ,去除最后一个逗号--修改

trim:可以增加(去除)前缀或者后缀

foreach:进行集合或者数组的遍历

bind:使用模糊查询进行字符的拼接

sql:提取公共sql片段

include:引入sql片段

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值