MyBatis中动态SQL使用

由于使用标签导致语句不显示的问题,所以部分sql语句用图片展示
MyBatis中常用动态SQL:

choose when otherwise
相当于java中的if else if else 也就是choose中有一个when条件成立时就会马上跳出,当所有when都不满足时执行otherwise

select * from test where 1 = 1
<choose>
    <when test="a!= null">
        and a= #{a}
    </when>
    <when test="b!= null">
        and b= #{b}
    </when>
    <otherwise>
        and c = #{c}
    </otherwise>
</choose>

set 在成功拼接前加上set且会忽略掉最后一个多余的逗号

update test
<set>
    <if test="a!= null and a!= ''">
        a= #{a},
    </if>
    <if test="b!= null and b!= ''">
        b= #{b},
    </if>
</set>
where c= #{c}

foreach演示

trim可以完成set或者是where标记的功能
select中
  这里写图片描述

  假如说a和b的值都不为null的话打印的SQL为:select * from test where a= ‘xx’ and b= ‘xx’
  在红色标记的地方是不存在第一个and的,上面两个属性的意思如下:
  prefix:前缀      
  prefixoverride:去掉第一个and或者是or
update中
  这里写图片描述

  假如说a和b的值都不为null的话打印的SQL为:update test set a=’xx’ , b=’xx’ where c=’x’
  在红色标记的地方不存在逗号,而且自动加了一个set前缀和where后缀,上面三个属性的意义如下,其中prefix意义如上:
  suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)
  suffix:后缀

猜你喜欢

转载自blog.csdn.net/qq_33157669/article/details/81541701
今日推荐