mybatis bind標簽


開門見山的說,平時寫模糊查詢,一直用${name},例如:

select * from table where name like '%${name}%'

后來知道了,這樣寫可能會引發sql注入,於是乎,要用到這樣一個標簽 bind,經過改正上面的sql可以變成

<bind name="bindeName" value="'%'+name+'%'"/>
SELECT * FROM table where name like #{bindeName}

大致就上面這個意思,不要在意一些細節。就相當於在bind標簽中的value值中,把需要的字符拼接好,然后用name中的值去代替拼接好的參數。

這個用法同樣用於一些防止更換數據庫的sql中。例如:

concat標簽,在mysql中,可以拼接多個字符,但是如果有一天,你的數據庫突然變成了oracle,concat就會報錯了,因為它只能接受兩個參數。

這個時候,bind同樣適用,如下:

開始的時候:

<if test=” userName != null and userName ! = ””>
  and username like concat ( '1',#{userName},'2'</if>

可以改成:

<if test=” userName != null and userName !=””> 
  <bind name= " userNameLike ” value = ”'1'+ userName + '2'”/>
  and username like #{userNameLike} 
</if>  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM