【MybBatis细节篇】MyBatis中#{}和${}的区别


在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时需要加单引号

${}的使用场景举例

当 SQL 语句中的元数据(如表名或列名)是动态生成的时候,字符串替换将会非常有用。 举个例子,如果你想 select 一个表任意一列的数据时,不需要这样写:

@Select("select * from user where id = #{id}")
User findById(@Param("id") long id);

@Select("select * from user where name = #{name}")
User findByName(@Param("name") String name);

@Select("select * from user where email = #{email}")
User findByEmail(@Param("email") String email);

// 其它的 "findByXxx" 方法

而是可以只写这样一个方法:

@Select("select * from user where ${column} = #{value}")
User findByColumn(@Param("column") String column, @Param("value") String value);

其中 ${column} 会被直接替换,而 #{value} 会使用 ? 预处理。 这样,就能完成同样的任务:

User userOfId1 = userMapper.findByColumn("id", 1L);
User userOfNameKid = userMapper.findByColumn("name", "kid");
User userOfEmail = userMapper.findByColumn("email", "noone@nowhere.com");

这种方式也同样适用于替换表名的情况。

提示: 用这种方式接受用户的输入,并用作语句参数是不安全的,会导致潜在的 SQL 注入攻击。因此,要么不允许用户输入这些字段,要么自行转义并检验这些参数。

  • 13
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李熠漾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值