最近在用mybatis,之前用過ibatis,總體來說差不多,不過還是遇到了不少問題,再次記錄下.
先給大家介紹下MyBatis中#{}和${}的區別,具體介紹如下:
1. #將傳入的數據都當成一個字符串,會對自動傳入的數據加一個雙引號。如:order by #user_id#,如果傳入的值是111,那么解析成sql時的值為order by "111", 如果傳入的值是id,則解析成的sql為order by "id".
2. $將傳入的數據直接顯示生成在sql中。如:order by $user_id$,如果傳入的值是111,那么解析成sql時的值為order by user_id, 如果傳入的值是id,則解析成的sql為order by id.
3. #方式能夠很大程度防止sql注入。
4.$方式無法防止Sql注入。
5.$方式一般用于傳入數據庫對象,例如傳入表名.
6.一般能用#的就別用$.
MyBatis排序時使用order by 動態參數時需要注意,用$而不是#
字符串替換
默認情況下,使用#{}格式的語法會導致MyBatis創建預處理語句屬性并以它為背景設置安全的值(比如?)。這樣做很安全,很迅速也是首選做法,有時你只是想直接在SQL語句中插入一個不改變的字符串。比如,像ORDER BY,你可以這樣來使用:
ORDER BY ${columnName}
這里MyBatis不會修改或轉義字符串。
重要:接受從用戶輸出的內容并提供給語句中不變的字符串,這樣做是不安全的。這會導致潛在的SQL注入攻擊,因此你不應該允許用戶輸入這些字段,或者通常自行轉義并檢查。
mybatis本身的說明:
1
2
3
4
5
|
String Substitution By default , using the #{} syntax will cause MyBatis to generate PreparedStatement properties and set the values safely against the PreparedStatement parameters (e.g. ?). 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. 使用#{}格式的語法在mybatis中使用Preparement語句來安全的設置值,執行sql類似下面的:
1
2
|
PreparedStatement ps = conn.prepareStatement(sql); ps.setInt( 1 ,id); |
這樣做的好處是:更安全,更迅速,通常也是首選做法。
2. 不過有時你只是想直接在 SQL 語句中插入一個不改變的字符串。比如,像 ORDER BY,你可以這樣來使用:
1
|
ORDER BY ${columnName} |
此時MyBatis 不會修改或轉義字符串。
這種方式類似于:
1
2
|
Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(sql); |
這種方式的缺點是:
以這種方式接受從用戶輸出的內容并提供給語句中不變的字符串是不安全的,會導致潛在的 SQL 注入攻擊,因此要么不允許用戶輸入這些字段,要么自行轉義并檢驗。
原文鏈接:http://www.cnblogs.com/baizhanshi/p/5778692.html