MyBatis动态sql语句

蚊子 2023年05月02日 383次浏览

前言

<if test="name!=null ">里面是无法使用<>(大于小于)的,转译也无法使用
int和Integer类型如果传入值是0,也是空和null的意思

sql语句里面可以使用,如果要用<>=等符号需要转译
参照表地址:https://www.jb51.net/article/221327.htm

where&if

它的意思是:
如果那个条件成立,会在where后面自动拼上and,如果n个条件成立,上一个条件后面自动拼and

       select * from no1
        <where>
            <if test="name!=null and name!='' ">
                and name_a = #{name}
            </if>
            <if test="id!=null and id!=0">
                and id = #{id}
            </if>
        </where>

choose

它类似java的switch,多条件只执行一个
在这里choose里面的when是if的意思
解释:

  1. 最终只执行一个判断,即使name和id都有值,也只执行name,两个都没值,就执行otherwise里面内容
  2. 在when和otherwise里面还可以使用<if test></if>
select * from no1
        <where>

          <choose>
            <when test="name!=null and name!='' ">
                and name_a = #{name}
            </when>
            <when test="id!=null and id!='' ">
                and id = #{id}
            </when>
            <otherwise>
                and name_a = '小明'
            </otherwise>
          </choose>
          
        </where>

set

用于更新语句,多个更新条件用(,)隔开
传统写法时候,如果你使用<if test></if>判断
你第一个条件不传值,只给第二个条件传的话,那么拼出来的sql语句就是
update no1 set ,name2='小白'

因此使用set来进行智能拼接(,)

   update no1
     <set>
     <if test="name!=null and name!='' ">
          name_a = #{name},
     </if>
     <if test="name2!=null and name2!=''">
          name_b = #{name2},
     </if>
     </set>
     where id=1

需要注意的是:

  1. 值的后面需要跟上(,)号
  2. 最后一个条件后面可加可不加image-1683040909116

其它

还有:trim、forEach、bind标签

trim:用于修正sql语句
forEach:将一个集合对象中的元素作为IN子句的参数值
bind:用于将一个参数绑定到一个Ognl表达式中,以便在后续的SQL语句中可以重复使用该参数或者对该参数进行一些操作,比如格式化日期,转换大小写等等