${}
$是將傳入的數據直接顯示生成sql語句
${}: 僅僅爲一個純碎的 string 替換,在動態 SQL 解析階段將會進行變量替換
#{}
#{}: 解析爲一個 JDBC 預編譯語句(prepared statement)的參數標記符,一個 #{ } 被解析爲一個參數佔位符 。
使用#可以很大程度上防止sql注入。(語句的拼接),但是如果使用在order by 中就需要使用$.
在大多數情況下還是經常使用#,但在不同情況下必須使用$.
select
#{selectClause} as id,sum(total) as total
from task_count
where type =#{type } province_id = #{provinceId } and city_id = #{cityId}
group by #{groupClause} having 1=1
Mybatis xml中有以上類似sql,運行後報錯
###Error querying database. Cause: org.postgresql.util.PSQLException: ERROR: column “dept_id” must appear in the GROUP BY clause or be used in an aggregate function
發現預編譯時sql如下:
select dept_id as id, sum(total) as total
from task_count
where type = ? and province_id = ? and city_id = ?
group by ? having 1=1