• 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 注入攻击,因此要么不允许用户输入这些字段,要么自行转义并检验。

    参考文献:

    【1】http://mybatis.github.io/mybatis-3/sqlmap-xml.html

    【2】https://mybatis.github.io/mybatis-3/zh/sqlmap-xml.html


    作者:Kei
    出处:http://www.cnblogs.com/ikei/
    本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.

     
  • 相关阅读:
    Linux命令总结--grep命令
    Linux命令总结--sed命令
    python函数--enumerate()方法
    python函数--index()方法
    在objc项目中使用常量的最佳实践
    iOS 开发 初级:应用内购买 In-App Purchase
    CFUUIDRef和CFStringRef-生成唯一标识符
    保留你的dSYM文件
    xcode 环境,多工程联编设置【转】
    ld: symbol dyld_stub_binding_helper not found, normally in crt1.o/dylib1.o/bundle1.o for architecture i386
  • 原文地址:https://www.cnblogs.com/ikei/p/7212507.html
Copyright © 2020-2023  润新知