<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也会去掉。