1. 程式人生 > >Mybatis中#{}與${}的區別

Mybatis中#{}與${}的區別

下面是一段英文簡介,描述了這兩種方式:

By default, using the #{} syntax will cause MyBatis to generate PreparedStatement properties and set the values safely against the PreparedStatement parameters.While this is safer, faster and almost always preferred, sometimes you just want to directly inject a string unmodified into the SQL Statement. 
For example, for ORDER BY, you might use something like this:ORDER BY ${columnName},Here MyBatis won't modify or escape the string.

NOTE It's not safe to accept input from a user and supply it to a statement unmodified in this way. This leads to potential SQL Injection attacks and therefore you should either disallow user input in these fields, or always perform your own escapes and checks.

       1、#將傳入的資料當成一個字串,會對自動傳入的資料加一個雙引號。例如order by #{id},如果傳入的值是111,那麼解析成sql時的值變為order by "111",如果傳入的值是id,在解析成sql為order by "id"。其實原sql語句通常寫成 order by #{id} 與order by #id#的效果一樣.

       2、$將傳入的資料直接顯示在sql語句中。例如 order by ${id},如果傳入的值是9則解析成sql語句為order by 9。

       3、#方式能夠很大程度上防止sql注入,而$無法防止sql的注入(${}會直接參與sql編譯。會影響sql語句的預編譯)。因此要麼不允許使用者輸入這些欄位,要麼自行轉義並檢驗。$一般用於傳入資料庫物件,例如傳入表名。一般能用#就別用$。mybatis排序時使用order by動態引數時需要住喲,使用$而不是#,${}一般用於order by的後面,Mybatis不會對這個引數進行任何的處理,直接生成了sql語句。

       4、在使用mybatis中還遇到<![CDATA[]]>的用法,在該符號內的語句,將不會被當成字串來處理,而是直接當成sql語句,比如要執行一個儲存過程。

原文連結:http://blog.csdn.net/qq_36127031/article/details/79451213