Mybatis中#和$的区别

01.$ 不安全 底层实现是Statement对象

select * from student where id=${id}

如果我们id传入的是11 编译之后

select * from student where id=11

 

# 安全 底层实现是PreparedStatement对象

select * from student where id=#{id}

如果我们id传入的是11 编译之后

select * from student where id=?

 

MyBatis启用了预编译功能,在SQL执行前,会先将上面的SQL发送给数据库进行编译;

执行时,如果传入参数为#{}格式的,将传入参数替换编译好的sql中的占位符“?”;

如果传入参数格式为${},则直接使用编译好的SQL就可以了。

因为SQL注入只能对编译过程起作用,所以使用#{}传入参数的方式可以很好地避免了SQL注入的问题。

 

02.在sql语句需要排序的时候

order by ${id}

只有在需要排序的时候 使用$ 

其他时候能用#绝对不用$

 

posted on 2017-09-16 00:07    阅读(289)  评论(0编辑  收藏  举报