Mybatis中防止Sql注入

一、什么是Sql注入

sql注入是一种代码注入技术,将恶意的sql插入到被执行的字段中,以不正当的手段多数据库信息进行操作。

在jdbc中使用一般使用PreparedStatement就是为了防止sql注入。

比如代码 :"select * from user where id =" + id;
正常执行不会出现问题,一旦被sql注入,比如将传入参数id=“3 or 1 = 1”,那么sql会变成
"select * from user where id = 3 or 1 = 1",这样全部用户信息就一览无遗了。

二、MyBatis中防止sql注入

下面是Mybatis的两种sql。

  
  

可以很清楚地看到,主要是#和$的区别。

#将传入的数据当成一个字符串,会对传入的数据加一个双引号,比如where id = “123”。

$将传入的数据直接显示在sql中,比如 where id = 123。

因此,#与$相比,#可以很大程度的防止sql注入,因为对sql做了预编译处理,因此在使用中一般使用#{}方式。

三、演示

在项目中配置log4j.properties,log4j.logger.cn.jxust.cms.dao=DEBUG。启动日志。

#方式

查看日志,sql进行了预编译,使用了占位符,防止了sql注入。  
[cn.jxust.cms.dao.UserMapper.selectByPrimaryKey] - ==>  Preparing: select id, stuId, username, password, type, info from user where id = ? 
  [cn.jxust.cms.dao.UserMapper.selectByPrimaryKey] - ==> Parameters: 1(Integer)
  [cn.jxust.cms.dao.UserMapper.selectByPrimaryKey] - <==      Total: 1

$方式

$传入的数据直接显示在sql中
 [cn.jxust.cms.dao.UserMapper.selectByPrimaryKey] - ==>  Preparing: select id, stuId, username, password, type, info from user where id = 1 
  [cn.jxust.cms.dao.UserMapper.selectByPrimaryKey] - ==> Parameters: 
  [cn.jxust.cms.dao.UserMapper.selectByPrimaryKey] - <==      Total: 1

​

附:使用$方式时,需要在mapper接口中使用@Param注解。否则会报There is no getter for property named 'id' in 'class java.lang.Integer'错误

User selectByPrimaryKey(@Param(value = "id") Integer id);

 

参考资料:

https://www.cnblogs.com/mmzs/p/8398405.html

你可能感兴趣的:(Mybatis)