Mybatis中两种取值符号区别

在使用Mybatis写sql语句时常会用到#{}和${}动态实现参数传递,这里就是来记录一下这两者的区别。

参考

MyBatis视频教程

[#{}与\({}的区别](https://blog.csdn.net/qian_qian_123/article/details/92844194?ops_request_misc=%25257B%252522request%25255Fid%252522%25253A%252522160759025519726885835134%252522%25252C%252522scm%252522%25253A%25252220140713.130102334..%252522%25257D&request_id=160759025519726885835134&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~baidu_landing_v2~default-3-92844194.pc_search_result_no_baidu_js&utm_term=#{}%E4%B8%8E\){}%E5%8C%BA%E5%88%AB)

区别

输入参数: parameterType

类型为简单类型(8个基本类型+String)

a

#{任意值}

${value},其中的标识符只能是value

b

#{}自动给String类型加上' '(自动类型转换)

${}原样输出,但是适合于动态排序(动态字段)

例:

1
select sno,sname,sage from student where sname = #{value}

等价

1
select sno,sname,sage from student where sname ='${value}'

动态排序

1
select sno,sname,sage from student order by ${value} asc

c

#{}可以防止SQL注入

${}不防止

原因