/ #{} 和 ${} 詳解
動態 sql 是 mybatis 的主要特性之一,在 mapper 中定義的參數傳到 xml 中之后,在查詢之前 mybatis 會對其進行動態解析。
mybatis 為我們提供了兩種支持動態 sql 的語法:#{} 以及 ${} 。
如: #{} : 根據參數的類型進行處理,比如傳入String類型,則會為參數加上雙引號。#{} 傳參在進行SQL預編譯時,會把參數部分用一個占位符 ? 代替,這樣可以防止 SQL注入。
如: ${} : 將參數取出不做任何處理,直接放入語句中,就是簡單的字符串替換,并且該參數會參加SQL的預編譯,需要手動過濾參數防止 SQL注入。
因此 mybatis 中優先使用 #{};當需要動態傳入 表名或列名 時,再考慮使用 ${} 。
其中 ${} 比較特殊, 他的應用場景是 需要動態傳入 表名或列名時使用。下面舉例:
這段代碼可以查出數據,但是根據業務來看是有問題的,他不能進行排序,因為 #{birthday} 解析出來后是一個 帶著雙引號的字符串,mysql找不到這樣的列名,因此不能進行排序。
<select id="getList" resultType="com.ccyang.UserDao">
select
u.user_id, u.user_name, u.user_type, u.age, u.sex, u.birthday
from
user u
<where>
u.user_age in <foreach collection="ages" item="item" index="index" open="(" separator="," close=")">#{item}</foreach>
and u.sex == "男"
<if test="u.user_name != null and u.user_name != ''"> AND u.user_name like CONCAT(CONCAT('%', #{userName}), '%')</if>
<if test="order_by!= null and order_by != ''"> order by #{order_by} DESC</if>
</where>
</select>
正確的寫法應該是使用 ${order_by},這樣解析后就是一個列名,然后才能對數據進行排序,已達到業務需求。
<!-- 條件查詢 -->
<select id="getList" resultType="com.ccyang.UserDao">
select
u.user_id, u.user_name, u.user_type, u.age, u.sex, u.birthday
from
user u
<where>
u.user_age in <foreach collection="ages" item="item" index="index" open="(" separator="," close=")">#{item}</foreach>
and u.sex == "男"
<if test="u.user_name != null and u.user_name != ''"> AND u.user_name like CONCAT(CONCAT('%', #{userName}), '%')</if>
<if test="order_by!= null and order_by != ''"> order by ${order_by} DESC</if>
</where>
</select>