簡述mybatis中獲取參數的兩種方法 #{ } 和 ${ } 的異同

mybatis中獲取接口方法中傳入參數的方式有兩種,一種是使用 #{ } 獲取,一種是使用 ${ } 獲取。兩種方式的不同點和相同點如下

不同點1

在傳入簡單類型(八大基本類型+String)的時候,只要parameterType屬性已經指定好了, #{ } 內可以填任意值, ${ } 內只能填value

代碼舉例:

  <!--當輸入參數是簡單類型的時候,八大基本類型+String,#{}裏面的值可以填任意字符-->
  <select id="query" parameterType="Integer" resultType="Student">
      -- 其中,#{}裏面的是參數,aaa可以爲任意值,studentId是列名,
      select *from student where studentId = #{aaa}
  </select>
  
  <!--還可以這樣寫,${}裏面只能寫value-->
  <select id="query" parameterType="Integer" resultType="Student">
      -- 其中,$裏面的是參數,value是固定值,studentId是列名
      select * from student where studentId = '${value}'
  </select>

不同點2

#{ } 會自動給String 類型加上引號,而 ${ } 不會,需要手工加,適合動態排序。以下是代碼舉例:

${ } 的使用

<!--
	錯誤寫法,假設我們傳入的值爲123,得到的sql語句爲
	select *from student where studentId = 123
-->
<select id="query" parameterType="int" resultType="Student">
    select *from student where studentId = ${value}
</select>

<!--
	正確寫法,假設我們傳入的值爲123,得到的sql語句爲
	select *from student where studentId = '123'
-->
<select id="query" parameterType="int" resultType="Student">
    select *from student where studentId = '${value}'
</select>

#{ } 的使用

<!--
	正確寫法,假設我們傳入的值爲123,得到的sql語句爲
	select *from student where studentId = '123'
	其中,aaa爲任意值
-->
<select id="query" parameterType="int" resultType="Student">
    select *from student where studentId = #{aaa}
</select>

有人會問,根據上面的情況,明顯可以感覺到 #{ } 方式比 ${ } 簡單,那爲什麼還要 ${} 呢?因爲在有些情況下,後者更適合,譬如模糊查詢,動態查詢的時候

<!--此時所需要的參數在引號外面,#{}顯然不合適,只有${}纔行-->
<select id="findStduent" parameterType="Student" resultType="Student">
    select * from student where studentName like '%${studentName}%'
</select>

不同點3

#{} 可以防止sql注入,而 ${} 不行

相同點

在面對傳入參數爲複雜類型的時候,兩者的使用方法相同

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章