From: https://blog.csdn.net/wobuaizhi/article/details/81874664
在使用mybatis的动态sql时,有时候遇到根据条件判断添加where后面的筛选条件。
会出现多余的“and”或者“or”,如下:
<select id="findBlog"
resultType="Blog">
SELECT * FROM BLOG
WHERE
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
</select>
如果第一个参数“state”为空,那么sql会变成下面这样,
select * from blog where and title like
如果两个if都为空,那么输出为,
select * from blog where
显然这样的sql执行时,会发生错误。
这时候使用where标签就可以解决这个问题,
<select id="findBlog"
resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
</where>
</select>
where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。
当然我们也可以用“trim”标签来处理。
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
prefix:前缀, prefixoverride:去掉第一个“and”或者是“or”
“trim”标签还有其他属性,
suffixoverride:去掉最后标记的字符(就像是上面的and一样)
suffix:后缀
参考文献:http://www.mybatis.org/mybatis-3/zh/dynamic-sql.html