mybatis中where标签和trim标签的使⽤
1 <where></where>标签的使⽤说明:
在使⽤mybatis的动态sql时,有时候遇到根据条件判断添加where后⾯的筛选条件。会出现多余的“and”或者“or”,如下:
<lect id="findBlog"
resultType="Blog">
burn down
SELECT * FROM BLOG
WHERE
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
</lect>
如果第⼀个参数“state”为空,那么sql会变成下⾯这样
lect * from blog where and title like 如果两个if都为空,那么输出为 lect * from blog where
显然这样的sql执⾏时,会发⽣错误。 这时候使⽤where标签就可以解决这个问题
<lect id="findBlog"
resultType="Blog">
issues是什么意思舌尖上的英国SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
西安新东方
</if>
哈佛大学录取分数线<if test="title != null">
AND title like #{title}fabricated
</if>
</where>
</lect>
where 元素只会在⾄少有⼀个⼦元素的条件返回 SQL ⼦句的情况下才去插⼊“WHERE”⼦句。⽽且,若语句的开头
为“AND”或“OR”,where 元素也会将它们去除。当然我们也可以⽤“trim”标签来处理
2 <trim></trim>标签的使⽤说明
trim标记是⼀个格式化的标记,可以完成t或者是where标记的功能,如下代码:澳门留学
lect * from urtreaty
<trim prefix="WHERE" prefixoverride="AND |OR">
<if test="name != null and name.length()>0"> AND name=#{name}</if>
<if test="gender != null and gender.length()>0"> AND gender=#{gender}</if>
</trim>
假如说name和gender的值都不为null的话打印的SQL为:lect * from ur where name = 'xx' and gender = 'xx' where后⾯是不存在第⼀个and的,上⾯两个属性的意思如下:
prefix:前缀
prefixoverride:去掉第⼀个and或者是or
update ur
<trim prefix="t" suffixoverride="," suffix=" where id = #{id} ">
<if test="name != null and name.length()>0"> name=#{name} , </if>
<if test="gender != null and gender.length()>0"> gender=#{gender} , </if>
同义词辨析>cellular
</trim>
假如说name和gender的值都不为null的话打印的SQL为:update ur t name='xx' , gender='xx' where id='x' 在where前⾯不存在逗号,⽽且⾃动加了⼀个t前缀和where后缀,上⾯三个属性的意义如下,其中prefix意义如上: suffixoverride:去掉最后⼀个逗号(也可以是其他的标记,就像是上⾯前缀中的and⼀样)
suffix:后缀