zoukankan      html  css  js  c++  java
  • MyBatis中#{}和${}的区别详解

    首先看一下下面两个sql语句的区别:

    <select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap">
    select id, username, password, role
    from user
    where username = #{username,jdbcType=VARCHAR}
    and password = #{password,jdbcType=VARCHAR}
    </select>
    <select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap">
    select id, username, password, role
    from user
    where username = ${username,jdbcType=VARCHAR}
    and password = ${password,jdbcType=VARCHAR}
    </select>

    mybatis中的#和$的区别:

    1、#将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。
    如:where username=#{username},如果传入的值是111,那么解析成sql时的值为where username="111", 如果传入的值是id,则解析成的sql为where username="id". 
    2、$将传入的数据直接显示生成在sql中。
    如:where username=${username},如果传入的值是111,那么解析成sql时的值为where username=111;

    3、针对上面的sql,如果传入的值是;drop table user;,

    那么第一条用#{}的sql解析为:select id, username, password, role from user where username=";drop table user;"

    那么第二条用${}的sql解析为:select id, username, password, role from user where username=;drop table user;

    这时候已经sql注入了。

    3、#方式能够很大程度防止sql注入,$方式无法防止Sql注入。
    4、$方式一般用于传入数据库对象,例如传入表名和列名,还有排序时使用order by动态参数时需要使用$ ,ORDER BY ${columnName}
    5、一般能用#的就别用$,若不得不使用“${xxx}”这样的参数,要手工地做好过滤工作,来防止sql注入攻击。
    6、在MyBatis中,“${xxx}”这样格式的参数会直接参与SQL编译,从而不能避免注入攻击。但涉及到动态表名和列名时,只能使用“${xxx}”这样的参数格式。所以,这样的参数需要我们在代码中手工进行处理来防止注入。
    【结论】在编写MyBatis的映射语句时,尽量采用“#{xxx}”这样的格式。若不得不使用“${xxx}”这样的参数,要手工地做好过滤工作,来防止SQL注入攻击。

  • 相关阅读:
    【原】使用Spring自带的JdbcTemplate。
    【原】MyBatis执行DDL:create table,drop table等等
    【转】java获取当前路径的几种方法
    【原】Java程序调用远程Shell脚本
    [转载] 使用Kettle进行数据迁移(ETL)
    appium原理
    python之global关键字的用法
    python之selenium定位(xpath)
    android 稳定性monkey测试
    python之selenium随记(几种等待的用法)
  • 原文地址:https://www.cnblogs.com/heqiyoujing/p/11204533.html
Copyright © 2011-2022 走看看