MyBatis动态sql语句

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

前言

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

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

where&if

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

  1. select * from no1
  2. <where>
  3. <if test="name!=null and name!='' ">
  4. and name_a = #{name}
  5. </if>
  6. <if test="id!=null and id!=0">
  7. and id = #{id}
  8. </if>
  9. </where>

choose

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

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

  3. <choose>
  4. <when test="name!=null and name!='' ">
  5. and name_a = #{name}
  6. </when>
  7. <when test="id!=null and id!='' ">
  8. and id = #{id}
  9. </when>
  10. <otherwise>
  11. and name_a = '小明'
  12. </otherwise>
  13. </choose>

  14. </where>

set

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

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

  1. update no1
  2. <set>
  3. <if test="name!=null and name!='' ">
  4. name_a = #{name},
  5. </if>
  6. <if test="name2!=null and name2!=''">
  7. name_b = #{name2},
  8. </if>
  9. </set>
  10. where id=1

需要注意的是:

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


其它

还有:trim、forEach、bind标签

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