1. 程式人生 > >mybatis動態sql中的where標籤的使用

mybatis動態sql中的where標籤的使用

在使用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:字尾