Mybatis ${}和#{}

Mybatis中传入参数会涉及到${}和#{}两种方式,但是什么时候用哪个,看过众多博客之后决定去官网看看。加上自己的试验之后总结如下:
Parameters :#{}
首先字面理解就是参数,可以指定类型。不指定类型,会默认为字符串类型,所以会
在传入的值上面加''(单引号)。或者预编译的时候,参数不符合规则,直接无法预编
译。
String Substitution :${}
先看看Mybatis是如何解释的:
By default, using the #{} syntax will cause MyBatis to generate PreparedStatement properties and set the values safely
against the PreparedStatement parameters (e.g. ?). While this is safer, faster and almost always preferred, sometimes
you just want to directly inject an unmodified string into the SQL Statement. For example, for ORDER BY, you
might use something like this:
            ORDER BY ${columnName}
Here MyBatis won't modify or escape the string.
NOTE: It's not safe to accept input from a user and supply it to a statement unmodified in this way. This leads to potential
SQL Injection attacks and therefore you should either disallow user input in these fields, or always perform your own escapes
and checks.
我的理解:${}会将传入的值,直接和SQL进行拼接,不会进行预编译。也就不会有类型不对无法预编译的问题了。
但是同样,如果没有预编译,直接执行拼接好的SQL就会有安全问题,比如是Drop table等语句呢?岂不是很危险。这既是【SQL注入】的问题了。
但是什么时候需要用到${}?${}的使用场景呢?
一般,由用户input的参数,选用#{},开发人员自己进行业务管控的参数可以用${},用户无法做到modify的参数。具体的场景就比如:select * from ${tablename},order by t.${},in(${}),etc.就比较适合用${}.
注:${param,jdbcType=String}这样的情况是不存在的,只有${param}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值