mybatis #{} 和 ${} 的区别

#{}是预编译处理,${}是字符串替换。

· Mybatis在处理#{}时,会将sql中的#{}替换为?号,调用PreparedStatement的set方法来赋值;

· Mybatis在处理{}时,就是把时,就是把{}替换成变量的值。

使用#{}可以有效的防止SQL注入,提高系统安全性。

 

一、什么是Sql注入

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

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

比如代码 :

1 "select * from user where id =" + id;


正常执行不会出现问题,一旦被sql注入,比如将传入参数id=“3 or 1 = 1”,那么sql会变成

1 "select * from user where id = 3 or 1 = 1"

 

这样全部用户信息就一览无遗了。


二、MyBatis中防止sql注入

下面是Mybatis的两种sql。

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

 

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

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

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

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

 

三、演示

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

#方式

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

 

$方式

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

 

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

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

 

posted @ 2022-04-07 16:56  r1-12king  阅读(83)  评论(0编辑  收藏  举报