天天看點

mybatis中bind标簽和concat的使用

首先,二種方式都可以用來模糊查詢,都能預防 SQL 注入。但是在更換資料庫情況下,bind标簽通用。

<if test=” userName != null and userName !=””>

and userName like concat('%' ,#{userName},'%')

</if>

使用concat函數連接配接字元串,在mysql中這個函數支援多個參數,但是在oracle中這個函數隻支援2個參數,由于不同資料庫之間的文法差異,更換資料庫,這些文法就需要重寫。可以用bind标簽來避免更換資料庫所帶來的一些麻煩。

bind 标簽可以使用 OGNL 表達式建立一個變量井将其綁定到上下文中。 

<bind name= " userNameBind ” value = ”’ % ’+ userNarne + ’ %’” />

<if test=” userName != null and userName !=””>

and userName like #{userNameBind}

</if>

bind 标簽的兩個屬性都是必選項, name 為綁定到上下文的變量名, value 為 OGNL 表 

達式。建立一個 bind 标簽的變量後 , 就可以在下面直接使用,使用 bind 拼接字元串不僅可 

以避免因更換資料庫而修改 SQL,也能預防 SQL 注入,還能實作多個引用userNameBind