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。

  <select id="selectByPrimaryKey" resultMap="BaseResultMap"         
                        parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" 
                         parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from user
    where id = ${id,jdbcType=INTEGER}
  </select>

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

# 将sql进行预编译"where id = ?",然后底层再使用PreparedStatement的set方法进行参数设置。

$ 将传入的数据直接将参数拼接在sql中,比如 “where id = 123”。

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

三、演示

在项目中配置log4j。方便查看sql日志。

#方式

查看日志,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'错误

扫描二维码关注公众号,回复: 11649726 查看本文章
User selectByPrimaryKey(@Param(value = "id") Integer id);

参考资料:

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

猜你喜欢

转载自blog.csdn.net/zh137289/article/details/90551305