<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </select>
若是这些条件没有一个能匹配上将会怎样?最终这条 SQL 会变成这样:yii
SELECT * FROM BLOG WHERE
这会致使查询失败。若是仅仅第二个条件匹配又会怎样?这条 SQL 最终会是这样:ide
SELECT * FROM BLOG WHERE AND title like ‘yiibai.com’
这个查询也会失败。这个问题不能简单的用条件句式来解决,若是你也曾经被迫这样写过,那么你极可能今后之后都不想再这样去写了。spa
MyBatis 有一个简单的处理,这在90%的状况下都会有用。而在不能使用的地方,你能够自定义处理方式来令其正常工做。一处简单的修改就能获得想要的效果:code
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG <where> <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </where> </select>
where 元素知道只有在一个以上的if条件有值的状况下才去插入“WHERE”子句。并且,若最后的内容是“AND”或“OR”开头的,where 元素也知道如何将他们去除。blog
若是 where 元素没有按正常套路出牌,咱们仍是能够经过自定义 trim 元素来定制咱们想要的功能。好比,和 where 元素等价的自定义 trim 元素为:it
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>