Mybaits <trim>标签的使用介绍

我们都知道trim标签有四个属性:

prefix:前缀增加的内容

prefixOverrides:前缀覆盖第一个判断的条件

suffix:后缀增加的内容

suffixOverrides:后缀覆盖最后一个判断的条件


下面给出例子:

例子1:

select * from student

<trim prefix="where" prefixoverride="and||or">

<if test="name!=null and name.length()>0">

and name=#{name}

</if>

<if test="sex!=null and sex.length()>0">

and sex=#{sex}

</if>

</trim>

如果name和sex的值不为null,则打印的sql语句为:

select * from student

where name='xx' and sex='xx'

红色的and因为有prefixoverride="and||or"被消掉了。

上面的两个属性的意思分别是:

prefix:前缀

prefixoverride:去掉第一个and或者or。


例子2:

update student

<trim prefix="set" suffixoverride="," suffix="where id=#{id}">

<iftest="name!=null and name.length()>0">

name=#{name},

</if>

<if test="sex!=null and sex.length()>0">

sex=#{sex},

</if>

</trim>

假如条件成立,打印的SQL语句为:

update student

set name='xx', sex='xx'

where id='xx'

红色标记的逗号被suffixoverride=","去掉了。

而且<trim>标签的前面和后面被自动添加了set和where。这三个属性的意义分别是:

suffixoverride:去掉最后一个逗号,(当然也可以是别的标记)

suffix:后缀

到这里大概应该明白了吧。





猜你喜欢

转载自blog.csdn.net/qq_40434646/article/details/80856219