在MyBatis 的映射配置文件中,动态传递参数有两种方式:
1、
#{} 占位符
2、
${} 拼接符
#{} 和 ${} 的区别
区别1
- #{} 为参数占位符 ?,即sql 预编译
- ${} 为字符串替换,即 sql 拼接
区别2、
- #{}:动态解析 -> 预编译 -> 执行
- ${}:动态解析 -> 编译 -> 执行
区别 3、
- #{} 的变量替换是在DBMS 中
- ${} 的变量替换是在 DBMS 外
区别 4、
- 变量替换后,#{} 对应的变量自动加上单引号
'' - 变量替换后,${} 对应的变量不会加上单引号
''
区别 5、
- #{} 能防止sql 注入
- ${} 不能防止sql 注入
#{} 和 ${} 的实例:假设传入参数为 1
实例步骤一
#{}:select * from t_user where uid=#{uid}
${}:select * from t_user where uid= '${uid}'
实例步骤二
#{}:select * from t_user where uid= ?
${}:select * from t_user where uid= '1'
实例步骤三
#{}:select * from t_user where uid= '1'
${}:select * from t_user where uid= '1'
#{} 和 ${} 的大括号中的值
单个参数的情形
#{}
无Mybaits默认值,可任意,且与参数无关  

${}
1、 使用Mybaits默认值value,即${value}  
2、使用自定义参数名,前提:在映射器接口方法的参数前加注解@Param("")  
多个参数的情形
#{}
1、使用Mybatis默认值arg0、arg1、arg2…或param1、param2、param3…  
2、 使用自定义参数名,前提: 在映射器接口方法的参数前加注解@Param("")  
错误的使用的多个参数的情况



${}
1、使用Mybatis默认值arg0、arg1、arg2…或param1、param2、param3…  
2、 使用自定义参数名,前提: 在映射器接口方法的参数前加注解@Param("")  
#{} 和 ${} 在使用中的技巧和建议
1、不论是单个参数,还是多个参数,一律都建议使用注解@Param("") 2、 能用 #{} 的地方就用 #{},不用或少用${} 3、表名作参数时,必须用${} 。如:select * from ${tableName} 4、order by 时,必须用 ${} 。如:select * from t_user order by ${columnName} 5、表名处用#{}会直接报错;order by后面用#{}排序不生效 6、使用 ${} 时,要注意何时加或不加单引号,即${} 和 '${}' 。一般字段类型为char或者varchar时需要加单引号
|