• mybatis中#{}和${}的区别


    首先我们看看mybatis本身的说明:

    String Substitution
    
    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 a string unmodified 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.

    从上文可以看出:

    1. 使用#{}格式的语法在mybatis中使用Preparement语句来安全的设置值,执行sql类似下面的:

    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setInt(1,id);

    这样做的好处是:更安全,更迅速,通常也是首选做法。

    2. 不过有时你只是想直接在 SQL 语句中插入一个不改变的字符串。比如,像 ORDER BY,你可以这样来使用:

    ORDER BY ${columnName}

    此时MyBatis 不会修改或转义字符串。

    这种方式类似于:

       Statement st = conn.createStatement();
           
          ResultSet rs = st.executeQuery(sql);

    这种方式的缺点是: 以这种方式接受从用户输出的内容并提供给语句中不变的字符串是不安全的,会导致潜在的 SQL 注入攻击,因此要么不允许用户输入这些字段,要么自行转义并检验。

    小结:

    Mybatis本身是基于JDBC封装的。

    #{para}是预编译处理(PreparedStatement)范畴的。

    ${para}是字符串替换。

    Mybatis在处理#时,会调用PreparedStatement的set系列方法来赋值;处理$时,就是把${para}替换成变量的值。

    使用#{para}可以有效的防止SQL注入,提高系统安全性。



    参见[文档](mybatis – MyBatis 3)

    http://www.mybatis.org/mybatis-3/sqlmap-xml.html#String_Substitution

  • 相关阅读:
    阿里云证书nginx无法访问带点的路径
    升级阿里云服务器文案
    html模板结合JS替换函数,生成新的记录
    企业使命、原景、战略、战略目标 详解
    Android之Handler用法总结【转】
    android activity的常用代码:关闭、传值、返回值、回调、网页、地图、短信、电话
    PHP十进制转36进制的函数
    [转]仓库管理必须知道的的50条重要知识
    [转]关于项目管理、软件开发的一些思考
    PHP5.5安装PHPRedis扩展
  • 原文地址:https://www.cnblogs.com/yizhiamumu/p/8998825.html
Copyright © 2020-2023  润新知