Mybatis <where>标签 - Just_Do - 博客园

复制代码; "复制代码")

<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 会变成这样:

SELECT * FROM BLOG WHERE

这会导致查询失败。如果仅仅第二个条件匹配又会怎样?这条 SQL 最终会是这样:

SELECT * FROM BLOG WHERE
AND title like ‘yiibai.com’

这个查询也会失败。这个问题不能简单的用条件句式来解决,如果你也曾经被迫这样写过,那么你很可能从此以后都不想再这样去写了。

MyBatis 有一个简单的处理,这在90%的情况下都会有用。而在不能使用的地方,你可以自定义处理方式来令其正常工作。一处简单的修改就能得到想要的效果:

复制代码; "复制代码")

<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 元素也知道如何将他们去除。

如果 where 元素没有按正常套路出牌,我们还是可以通过自定义 trim 元素来定制我们想要的功能。比如,和 where 元素等价的自定义 trim 元素为:

<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>


Original url: Access
Created at: 2020-06-15 17:25:51
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论