Mybatis中#{}和${}输入参数的区别

18 篇文章 1 订阅
11 篇文章 0 订阅

#{}

mybatis 会进行预编译,比如(假设ID=6):

select * from user where id=#{ID}

会先编译成

select * from user where id=?

然后用ID的值(6)替代?

#{}的优势

更安全

如果传入的值值中有#(#在sql中表示注释)使用#{},不会使#后面的sql失效,当传入的name参数中有#,比如hh#:

select * from user where name=#{name} and id=#{ID}

执行的sql为

select * from user where name="hh#" and id=6

如果用${}

select * from user where name=${name} and id=${ID}

则执行的sql为

select * from user where name="hh" # and id=6

因为#表示注释所以执行效果相当于

select * from user where name="hh"

可以指定其它属性

如果name参数传入的值为null,mybatis会默认name值为other类型 ,但是oracle数据库不能处理other类型,因此会报不能识别的错误。此时就可以用jdbcType属性指定类型

select * from user where name=#{name, jdbcType=null} and id=${ID}

当然也可以在mybatis配置文件中进行配置

<settings>
        <setting name="jdbcTypeForNull" value="NULL"/>
    </settings>

${}

mybatis 会直接进行编译,比如(假设ID=6):

select * from user where id=${ID}

会直接编译成

select * from user where id=6

${}的优势

jdbc不支持占位符的地方可以使用${}进行取值,比如表名和排序字段
select * from ${user} where name=#{name} and id=#{ID} order by ${name}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值