Mybatis 中$与#的区别

一 : mybatis中 $与#

1.数据类型匹配

#:会进行预编译,而且进行类型匹配

$:不进行数据类型匹配

2.实现方式

#:用于变量替换

$:实质上是字符串拼接

3.#和$的使用场景

(1)变量的传递,必须使用#,使用#{}就等于使用了PrepareStatement这种占位符的形式,提高效率。可以防止sql注入等等问题。#方式一般用于传入添加,修改的值或查询,删除的where条件 id值

select * from t_user where name = #{param}

(2)$只是只是简单的字符串拼接,要特别小心sql注入问题,对应非变量部分,只能用$。$方式一般用于传入数据库对象,比如这种group by 字段 ,order by 字段,表名,字段名等没法使用占位符的就需要使用${}

select count(*), from t_user group by ${param}

(3)能同时使用#和$的时候,最好用#。

在mybatis中的$与#都是在sql中动态的传入参数。

eg:select id,name,age from student where name=#{name}  这个name是动态的,可变的。当你传入什么样的值,就会根据你传入的值执行sql语句。

二 : 使用$与#

   #{}: 解析为一个 JDBC 预编译语句(prepared statement)的参数标记符,一个 #{ } 被解析为一个参数占位符 。

   ${}: 仅仅为一个纯碎的 string 替换,在动态 SQL 解析阶段将会进行变量替换。

  name-->cy

 eg:  select id,name,age from student where name=#{name}   -- name='cy'

       select id,name,age from student where name=${name}    -- name=cy

1 #是将传入的值当做字符串的形式

eg:select id,name,age from student where id =#{id},当前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id ='1'.

2 $是将传入的数据直接显示生成sql语句

eg:select id,name,age from student where id =${id},当前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id = 1.

3 使用#可以很大程度上防止sql注入。(语句的拼接)

4 但是如果使用在order by 中就需要使用 $.

5 在大多数情况下还是经常使用#,但在不同情况下必须使用$. 

我觉得#与的区别最大在于:#{} 传入值时,sql解析时,参数是带引号的,而的区别最大在于:#{} 传入值时,sql解析时,参数是带引号的,而{}穿入值,sql解析时,参数是不带引号的。

 

参考:

https://www.cnblogs.com/hellokitty1/p/6007801.html

https://blog.csdn.net/weixin_39220472/article/details/79656122

posted @ 2019-09-18 11:09  MengW9  阅读(361)  评论(0编辑  收藏  举报