简述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注入,而 ${} 不行

相同点

在面对传入参数为复杂类型的时候,两者的使用方法相同

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