mybatis 中使用 sqlMap 进行 sql 查询时,经常需要动态传递参数,例如我们需要根据用户的姓名来筛选用户时,sql 如下:

  1. select * from user where name = "ruhua";

上述 sql 中,我们希望 name 后的参数 "ruhua" 是动态可变的,即不同的时刻根据不同的姓名来查询用户。在 sqlMap 的 xml 文件中使用如下的 sql 可以实现动态传递参数 name:

  1. select * from user where name = #{name};

或者

  1. select * from user where name = '${name}';

对于上述这种查询情况来说,使用 #{ } 和 ${ } 的结果是相同的,但是在某些情况下,我们只能使用二者其一。

'#' 与 '$'

区别

动态 SQL 是 mybatis 的强大特性之一,也是它优于其他 ORM 框架的一个重要原因。mybatis 在对 sql 语句进行预编译之前,会对 sql 进行动态解析,解析为一个 BoundSql 对象,也是在此处对动态 SQL 进行处理的。

在动态 SQL 解析阶段, #{ } 和 ${ } 会有不同的表现:

#{ } 解析为一个 JDBC 预编译语句(prepared statement)的参数标记符。

例如,sqlMap 中如下的 sql 语句

  1. select * from user where name = #{name};

解析为:

  1. select * from user where name = ?;

一个 #{ } 被解析为一个参数占位符 ? 。

而,

${ } 仅仅为一个纯碎的 string 替换,在动态 SQL 解析阶段将会进行变量替换

例如,sqlMap 中如下的 sql

  1. select * from user where name = '${name}';

当我们传递的参数为 "ruhua" 时,上述 sql 的解析为:

  1. select * from user where name = "ruhua";

预编译之前的 SQL 语句已经不包含变量 name 了。

综上所得, ${ } 的变量的替换阶段是在动态 SQL 解析阶段,而 #{ }的变量的替换是在 DBMS 中。

用法 tips

1、能使用 #{ } 的地方就用 #{ }

首先这是为了性能考虑的,相同的预编译 sql 可以重复利用。

其次,${ } 在预编译之前已经被变量替换了,这会存在 sql 注入问题。例如,如下的 sql,

  1. select * from ${tableName} where name = #{name}

假如,我们的参数 tableName 为 user; delete user; --,那么 SQL 动态解析阶段之后,预编译之前的 sql 将变为

  1. select * from user; delete user; -- where name = ?;

-- 之后的语句将作为注释,不起作用,因此本来的一条查询语句偷偷的包含了一个删除表数据的 SQL!

2、表名作为变量时,必须使用 ${ }

这是因为,表名是字符串,使用 sql 占位符替换字符串时会带上单引号 '',这会导致 sql 语法错误,例如:

  1. select * from #{tableName} where name = #{name};

预编译之后的sql 变为:

  1. select * from ? where name = ?;

假设我们传入的参数为 tableName = "user" , name = "ruhua",那么在占位符进行变量替换后,sql 语句变为

  1. select * from 'user' where name='ruhua';

上述 sql 语句是存在语法错误的,表名不能加单引号 ''(注意,反引号 ``是可以的)。

sql预编译

定义

sql 预编译指的是数据库驱动在发送 sql 语句和参数给 DBMS 之前对 sql 语句进行编译,这样 DBMS 执行 sql 时,就不需要重新编译。

为什么需要预编译

JDBC 中使用对象 PreparedStatement 来抽象预编译语句,使用预编译

  1. 预编译阶段可以优化 sql 的执行
    预编译之后的 sql 多数情况下可以直接执行,DBMS 不需要再次编译,越复杂的sql,编译的复杂度将越大,预编译阶段可以合并多次操作为一个操作。

  2. 预编译语句对象可以重复利用
    把一个 sql 预编译后产生的 PreparedStatement 对象缓存下来,下次对于同一个sql,可以直接使用这个缓存的 PreparedState 对象。

mybatis 默认情况下,将对所有的 sql 进行预编译。

mysql预编译源码解析

mysql 的预编译源码在 com.mysql.jdbc.ConnectionImpl 类中,如下:

  1. public synchronized java.sql.PreparedStatement prepareStatement(String sql,
  2. int resultSetType, int resultSetConcurrency) throws SQLException {
  3. checkClosed();
  4. //
  5. // FIXME: Create warnings if can't create results of the given
  6. // type or concurrency
  7. //
  8. PreparedStatement pStmt = null;
  9. boolean canServerPrepare = true;
  10. // 不同的数据库系统对sql进行语法转换
  11. String nativeSql = getProcessEscapeCodesForPrepStmts() ? nativeSQL(sql): sql;
  12. // 判断是否可以进行服务器端预编译
  13. if (this.useServerPreparedStmts && getEmulateUnsupportedPstmts()) {
  14. canServerPrepare = canHandleAsServerPreparedStatement(nativeSql);
  15. }
  16. // 如果可以进行服务器端预编译
  17. if (this.useServerPreparedStmts && canServerPrepare) {
  18. // 是否缓存了PreparedStatement对象
  19. if (this.getCachePreparedStatements()) {
  20. synchronized (this.serverSideStatementCache) {
  21. // 从缓存中获取缓存的PreparedStatement对象
  22. pStmt = (com.mysql.jdbc.ServerPreparedStatement)this.serverSideStatementCache.remove(sql);
  23. if (pStmt != null) {
  24. // 缓存中存在对象时对原 sqlStatement 进行参数清空等
  25. ((com.mysql.jdbc.ServerPreparedStatement)pStmt).setClosed(false);
  26. pStmt.clearParameters();
  27. }
  28. if (pStmt == null) {
  29. try {
  30. // 如果缓存中不存在,则调用服务器端(数据库)进行预编译
  31. pStmt = ServerPreparedStatement.getInstance(getLoadBalanceSafeProxy(), nativeSql,
  32. this.database, resultSetType, resultSetConcurrency);
  33. if (sql.length() < getPreparedStatementCacheSqlLimit()) {
  34. ((com.mysql.jdbc.ServerPreparedStatement)pStmt).isCached = true;
  35. }
  36. // 设置返回类型以及并发类型
  37. pStmt.setResultSetType(resultSetType);
  38. pStmt.setResultSetConcurrency(resultSetConcurrency);
  39. } catch (SQLException sqlEx) {
  40. // Punt, if necessary
  41. if (getEmulateUnsupportedPstmts()) {
  42. pStmt = (PreparedStatement) clientPrepareStatement(nativeSql, resultSetType, resultSetConcurrency, false);
  43. if (sql.length() < getPreparedStatementCacheSqlLimit()) {
  44. this.serverSideStatementCheckCache.put(sql, Boolean.FALSE);
  45. }
  46. } else {
  47. throw sqlEx;
  48. }
  49. }
  50. }
  51. }
  52. } else {
  53. // 未启用缓存时,直接调用服务器端进行预编译
  54. try {
  55. pStmt = ServerPreparedStatement.getInstance(getLoadBalanceSafeProxy(), nativeSql,
  56. this.database, resultSetType, resultSetConcurrency);
  57. pStmt.setResultSetType(resultSetType);
  58. pStmt.setResultSetConcurrency(resultSetConcurrency);
  59. } catch (SQLException sqlEx) {
  60. // Punt, if necessary
  61. if (getEmulateUnsupportedPstmts()) {
  62. pStmt = (PreparedStatement) clientPrepareStatement(nativeSql, resultSetType, resultSetConcurrency, false);
  63. } else {
  64. throw sqlEx;
  65. }
  66. }
  67. }
  68. } else {
  69. // 不支持服务器端预编译时调用客户端预编译(不需要数据库 connection )
  70. pStmt = (PreparedStatement) clientPrepareStatement(nativeSql, resultSetType, resultSetConcurrency, false);
  71. }
  72. return pStmt;
  73. }

流程图如下所示:

mybatis之sql动态解析以及预编译源码

mybatis sql 动态解析

mybatis 在调用 connection 进行 sql 预编译之前,会对sql语句进行动态解析,动态解析主要包含如下的功能:

  • 占位符的处理

  • 动态sql的处理

  • 参数类型校验

mybatis强大的动态SQL功能的具体实现就在此。动态解析涉及的东西太多,以后再讨论。

mybatis深入理解(一)之 # 与 $ 区别以及 sql 预编译的更多相关文章

  1. 从Mybatis中#和$的区别到SQL预编译

    #和$的区别 Mybatis中参数传递可以通过#和$设置.它们的区别是什么呢? # Mybatis在解析SQL语句时,sql语句中的参数会被预编译为占位符问号? $ Mybatis在解析SQL语句时, ...

  2. mybatis深入理解之 # 与 $ 区别以及 sql 预编译

    mybatis 中使用 sqlMap 进行 sql 查询时,经常需要动态传递参数,例如我们需要根据用户的姓名来筛选用户时,sql 如下: select * from user where name = ...

  3. mybatis之 # 与 $ 区别以及 sql 预编译

    mybatis 中使用 sqlMap 进行 sql 查询时,经常需要动态传递参数,例如我们需要根据用户的姓名来筛选用户时,sql 如下: select * from user where name = ...

  4. mybatis中#{}与${}的差别(如何防止sql注入)

    默认情况下,使用#{}语法,MyBatis会产生PreparedStatement语句中,并且安全的设置PreparedStatement参数,这个过程中MyBatis会进行必要的安全检查和转义. # ...

  5. mybatis以及预编译如何防止SQL注入

    SQL注入是一种代码注入技术,用于攻击数据驱动的应用,恶意的SQL语句被插入到执行的实体字段中(例如,为了转储数据库内容给攻击者).[摘自] SQL injection - Wikipedia SQL ...

  6. SQL注入和Mybatis预编译防止SQL注入

    什么是SQL注入?? 所谓SQL注入,就是通过把SQL命令插入到Web表单提交或页面请求url的查询字符串,最终达到欺骗服务器执行恶意的SQL命令.具体来说,它是利用现有应用程序,将(恶意)的SQL命 ...

  7. 静态代理、动态代理与Mybatis的理解

    静态代理.动态代理与Mybatis的理解 这里的代理与设计模式中的代理模式密切相关,代理模式的主要作用是为其他对象提供一种控制对这个对象的访问方法,即在一个对象不适合或者不能直接引用另一个对象时,代理 ...

  8. mybatis学习$与#号取值区别

    1,多个参数传递用map或实体封装后再传给myBatis, mybatis学习$与#号取值区别 #{} 1.加了单引号,  2.#号写是可以防止sql注入,比较安全 select * from use ...

  9. mybatis中xml文件的${}和#{}区别

    之前的笔记:#{}相当于JDBC的? ${}是字符串连接符,如果入参为普通类型{}中只写value 在项目中要实现所有业务批量提交的功能,实现方式,把表名,表主键字段当做参数传递,在xml文件中全部使 ...

随机推荐

  1. bzoj 2118: 墨墨的等式 spfa

    题目: 墨墨突然对等式很感兴趣,他正在研究\(a_1x_1+a_2y_2+ ... +a_nx_n=B\)存在非负整数解的条件,他要求你编写一个程序,给定\(N,\{a_n\}\)以及\(B\)的取值 ...

  2. XP系统下显示文件或文件的安全选项卡

    在很多的时候,我们需要设置文件或文件夹的权限,这里一般就要用到安全选项卡,但在xp系统下,默认是不显示的,如何调出我们的“安全”选项卡呢? 具体做法:点击“工具”菜单下的"文件夹选项(o). ...

  3. delete操作符

    delete操作符通常用来删除对象的属性: Js代码     var o = { x: 1 }; delete o.x; // true o.x; // undefined 而不是一般的变量: Js代 ...

  4. 在Eclipse中用JDBC连接Mysql数据库

    一.配置要求 JDK(下载http://www.oracle.com/technetwork/java/javase/downloads/index.html) Mysql(下载http://www. ...

  5. Springboot监控之一:SpringBoot四大神器之Actuator之2--spring boot健康检查对Redis的连接检查的调整

    因为项目里面用到了redis集群,但并不是用spring boot的配置方式,启动后项目健康检查老是检查redis的时候状态为down,导致注册到eureka后项目状态也是down.问下能不能设置sp ...

  6. css中的块级和内联元素

    块级元素: 首先说明display是块级元素,会单独站一行,如 代码: <!DOCTYPE html> <html> <head lang="en"& ...

  7. [jQuery] 按回车键实现登录

    Jquery按回车键提交实现登录的方式分为两种: 1.按钮提交 2.表单提交 1.按钮提交 $("#LoginIn").off('click').on('click', funct ...

  8. 5.JasperReports学习笔记5-其它数据生成动态的报表(WEB)

    转自:http://www.blogjava.net/vjame/archive/2013/10/12/404908.html 一.空数据(Empty Datasources) 就是说JRXML文件里 ...

  9. MS-SQL使用xp_cmdshell命令导出数据到excel

    exec master..xp_cmdshell 'bcp "select c.Category_Title as 标题,p.Category_Title as 所属分类 from ltbl ...

  10. How to Write a Spelling Corrector用java 写拼写检查器 Java实现 以备查验

    import java.io.*;import java.util.*;import java.util.regex.*; class Spelling { private final HashMap ...