Mybatis中#{}和${}的区别是什么?

是什么?

Mybatis中的#{}${}都可以把传入的参数拼到SQL中。
#{}是预编译处理、是占位符, ${}是字符串替换、是拼接符。

核心思想是:确保sql语句中 String型参数 的最外层由单引号包裹;特殊字符普通化。


为什么?

  • Mybatis在处理#{}时,会将sql中的#{}替换为?号,调用PreparedStatementset方法来赋值;
  • Mybatis 在处理${}时, 就是把${}替换成变量的值,调⽤ Statement 来赋值

看看PreparedStatementStatement的区别:

PreparedStatement 接口是 Statement 的子接口,它表示一条预编译过的 SQL 语句,并对参数中的特殊字符进行转义,使用StringBuild对象来容纳sql语句的每个字符,最后再把StringBuild对象转String。

  • Statement用于执行静态sql语句,在执行时,必须指定一个事先准备好的sql语句,直接交给数据库执行。
SQL="select * from user where username = ' " + username + " ' ";
username=hello'; delete from user where id='1
最终的Sql就是
  SQL="select * from user where username = ' hello'; delete from user where id='1 '";
  • PrepareStatement是预编译的sql语句对象,sql语句被预编译并保存在对象中。被封装的sql语句代表某一类操作,语句中可以包含动态参数“?”,在执行时可以为“?”动态设置参数值。
select * from user where name = #{name} and password = #{password} 将转为
select * from user where name = 'zhouyu' and password = '1 or 1=1'

注意:SQL中的字符串使用单引号表示!

  • 使用PrepareStatement对象执行sql时,sql被交给数据库进行解析和编译,然后被放到命令缓冲区,每当执行同一个PrepareStatement对象时,它就会被解析一次,但不会被再次编译。而statement则是每次都要从0开始。
    此时参数只能填充,而不会作为SQL的一部分。
    在缓冲区可以发现预编译的命令,并且可以重用。

怎么用?

  • 在实际项目中如果能够使用preparestatement还是建议使用preparestatement
  • 单条数据statement更快
  • 批处理时PrepareStatement可以减少编译次数提高数据库性能。
  • 安全性上来说更要使用PrepareStatement,也就是#{}
posted @ 2021-08-29 12:08  快乐的海盗  阅读(429)  评论(0编辑  收藏  举报