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

相同点

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大青儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值