mybatis动态SQL简单使用

mybatis动态SQL

  1. if
  2. choose(when,otherwise)
  3. trim(where, set)
  4. foreach
  • if元素

    • <select>
      	select * from dual where 1=1
        <if test="'1'=='1' and '2'!='1'">
        	and 2=2
        </if>
      </select>
      
  • choose元素

    • <select>
      	select * from dual where 1=1
        <choose><!--switch-->
        	<when test="'1'=='1' and '2'!='1'"><!--case-->
          	and 2=2
          </when>
          <when test="'2'=='2' and '2'!='1'">
          	and 3=3
          </when>
          <otherwise><!--default-->
          	and xxx is not null;
          </otherwise>
        </choose>
      </select>
      
  • trim|where|set元素

    • <!--
      trim and where
      prefix-语句前缀
      predixOverrides-要去掉开头哪种字符
      -->
      <select>
      	select * from dual
        <trim prefix="where" predixOverrides="and">
        <if test="'1'=='1' and '2'!='1'">
        	and 2=2
        </if>
        </trim>
      </select>
      
    • <!--
      set遇到逗号会把对应的逗号去掉
      -->
      <update>
      	update user
        <set>
        	<if test="name!=null">
          	name=#{name},
          </if>
        </set>
      </update>
      
      <!--
      trim
      suffixOverides-要去掉结尾哪种字符
      -->
      <update>
      	update user
        	<trim profix="set" suffixOverides=",">
        	<if test="name!=null">
          	name=#{name},
          </if>
          </trim>
      </update>
      
  • foreach

    • <!--
      collection配置的是传递过来的参数名称,他可以是数组、list、set等集合
      item配置的循环中的具体元素
      index是指元素在集合的位置下标
      open和colse配置的是以什么符号将这些元素包装起来
      separator是各个元素的间隔符
      -->
      <select>
      	select * from user where id in
        <foreach item="id" index="index" collection="userlist" open="(" separator="," close=")">
      		#{id}
        </foreach>
      </select>
      
  • bind元素

    • 作用:定义sql的上下文变量,可定义多个使用

    • <select>
        <bind name = "pattern" value="'%'+ name +'%'"
      	select id,name from user where name like #{name}
      </select>
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值