zoukankan      html  css  js  c++  java
  • mybatis中的#{}和${}

    1、在MyBatis 的映射配置文件中,动态传递参数有两种方式:

    (1)#{} 占位符

    (2)${} 拼接符

    2、#{} 和 ${} 的区别

    (1)

      1)#{} 为参数占位符 ?,即sql 预编译

      2)${} 为字符串替换,即 sql 拼接

    (2)

      1)#{}:动态解析 -> 预编译 -> 执行

      2)${}:动态解析 -> 编译 -> 执行

    (3)

      1)#{} 的变量替换是在DBMS 中

      2)${} 的变量替换是在 DBMS 外

    (4)

      1)变量替换后,#{} 对应的变量自动加上单引号 ''

      2)变量替换后,${} 对应的变量不会加上单引号 ''

    (5)

      1)#{} 能防止sql 注入

      2)${} 不能防止sql 注入

    3、#{} 和 ${} 的实例:假设传入参数为 1

    (1)开始

      1)#{}:select * from t_user where uid=#{uid}

      2)${}:select * from t_user where uid= '${uid}'

    (2)然后

    1)#{}:select * from t_user where uid= ?

    2)${}:select * from t_user where uid= '1'

    (3)最后

      1)#{}:select * from t_user where uid= '1'

      2)${}:select * from t_user where uid= '1'

    4、#{} 和 ${} 的大括号中的值

    (1)单个参数的情形

      1)#{}

        无MyBatis 默认值,可任意,且与参数名无关

      2)${}

        <1>使用 MyBatis 默认值 value,即 ${value}

        <2>使用自定义参数名,前提:在映射器接口方法的参数前加注解@Param("")

    (2)多个参数的情形

      1)#{}

        <1>使用MyBatis 默认值 arg0、arg1、arg2 … 或 param1、param2、param3 …

        <2>使用自定义参数名,前提:在映射器接口方法的参数前加注解@Param("")

      2)${}

        <1>使用MyBatis 默认值 arg0、arg1、arg2 … 或 param1、param2、param3 …

        <2>使用自定义参数名,前提:在映射器接口方法的参数前加注解@Param("")

        注:@Param("") 是 @Param(value="") 的简写

    5、#{} 和 ${} 在使用中的技巧和建议

    (1)不论是单个参数,还是多个参数,一律都建议使用注解@Param("")

    (2)能用 #{} 的地方就用 #{},不用或少用 ${}

    (3)表名作参数时,必须用 ${}。如:select * from ${tableName}

    (4)order by 时,必须用 ${}。如:select * from t_user order by ${columnName}

    (5)使用 ${} 时,要注意何时加或不加单引号,即 ${} 和 '${}'

    参考:https://blog.csdn.net/siwuxie095/article/details/79190856

  • 相关阅读:
    数据库概论练习题第一章整理(1)
    eclipse启动报错 see the log file的解决办法
    有关myeclipse8.5.0搭建java web项目环境【未整理】
    Pycharm安装及配置
    Anaconda安装及配置环境
    C#操作字符串方法总结
    SQL语句中的换行符
    委托
    基类VS接口
    泛型及其继承和同一性
  • 原文地址:https://www.cnblogs.com/xiao-lin-unit/p/13644004.html
Copyright © 2011-2022 走看看