1. 程式人生 > 實用技巧 >mybatis bind 標籤

mybatis bind 標籤

bind 標籤可以使用 OGNL 表示式建立一個變數井將其繫結到上下文中。在前面的例子中,
UserMapper.xml 有一個 selectByUser 方法,這個方法用到了 like 查詢條件,部分程式碼如下 。

<if test=” userNarne != null and userNarne ! = ””>
and user name like concat ( ’ 毛 ’, #{ userNarne },’ 氈 ’ )
</if>

使用 con cat 函式連線字串,在 MySQL 中,這個函式支援多個引數,但在 Oracle 中只

支援兩個引數。由於不 同資料庫之間的語法差異 ,如果更換資料庫,有些 SQL 語句可能就需要
重寫。針對這種情況,可 以使用 bind 標籤來避免由於更換資料庫帶來的一些麻煩。將上面的
方法改為 bind 方式後,程式碼如下。

<if test=userNarne != null and userNarne !=””>
<bind narne= " userNarneLike ” value = ”’ 草 ’+ userNarne + ’ 每 ’” / 〉
and user name like #{userNarneLike}
</if>

bind 標籤的兩個屬性都是必選項, name 為繫結到上下文的變數名, va l ue 為 OGNL 表
達式。建立一個 bind 標籤的變數後 , 就可以在下面直接使用,使用 bind 拼接字串不僅可
以避免因更換資料庫而修改 SQL,也能預防 SQL 注入。