Mybatis通配符

Mybatis通配符

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

       select id,name,age from student where name=#{name} 

    这个name是动态的,可变的。当你传入什么样的值,就会根据你传入的值执行sql语句。                                                                        

1. MyBatis中使用parameterType向SQL语句传参,parameterType后的类型可以是基本类型int,String,HashMap和java自定义类型等

2.在xml写SQL都是用#,如#{param}。但是有时会看到用$的时候,如${param}

3. 那么$ 和 # ,有什么区别呢?

    1) 通配符 "#" 是将传入的值当做字符串的形式,如:

    select id,name,age from user where id=#{id}

         当前端把id值1,传入到后台的时候,就相当于 (#{} 传入值时,sql解析时,参数是带引号的)      

  1.     select id,name,age from student where id ='1'.

    2)通配符 "$" 是将传入的数据直接显示生成sql语句,如:

    select id, name, age from user where id=${id}

         当前端把id值1,传入到后台的时候,就相当于 (${}穿入值,sql解析时,参数是不带引号的)

    select id,name,age from student where id = 1.

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

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

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

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

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

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

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

猜你喜欢

转载自blog.csdn.net/codertnt/article/details/80897192