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);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!