<select id="queryBlogIf" resultType="blog" parameterType="map">
select * from mybatis.blog where
<if test="title!=null">
title like concat('%',#{title},'%')
</if>
<if test="author!=null">
and author = #{author}
</if>
</select>
正常使用if标签应该是这样的,但是这样会导致一个问题。
就是在只查询author的时候,mybatis不会自动的去除掉 and,而导致SQL语句变成
select * from mybatis.blog where and author = ?
这样就会出问题

<where>标签正是用来解决这个问题的, 如果是第一个条件不满足,匹配后面的条件,它会自动的去除后面条件中的and符号。
<select id="queryBlogIf" resultType="blog" parameterType="map">
select * from mybatis.blog
<where>
<if test="title!=null">
title like concat('%',#{title},'%')
</if>
<if test="author!=null">
and author = #{author}
</if>
</where>
</select>
如果不传递参数的话,where也会去掉。
本文详细介绍了MyBatis中if和where标签的用法,特别是它们在动态SQL语句中的作用。当查询条件为空时,where标签能够智能移除多余的'and',避免SQL语法错误。通过实例展示了正确使用这两个标签的方式,帮助开发者更好地理解和应用MyBatis的动态SQL功能。
1万+

被折叠的 条评论
为什么被折叠?



