Mybatis中#{}和${}的区别是什么?
#{}和${}的区别是什么?
1)#{}是预编译处理,$ {}是字符串替换。
2)使用MyBatis在处理#{}时,会将SQL中的#{}替换为?号,使用PreparedStatement的set方法来赋值;MyBatis在处理 $ { } 时,就是把 ${ } 替换成变量的值。
3)使用 #{} 可以有效的防止SQL注入。预编译是提前对SQL语句进行预编译,而其后注入的参数将不会再进行SQL编译。SQL注入是发生在编译的过程中,因为恶意注入了某些特殊字符,最后被编译成了恶意的执行操作。
在Mybatis中当你进行数据库查询时SQL语句通过#{id}传值
<select id="SelecUserById" resultType="com.hy.User" ">
select *from user where id=#{id};
</select>
通过打印日志出来可以看到sql中的#{}被替换为?号
DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 764577347.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@2d928643]
DEBUG [main] - ==> Preparing: select *from user where id=?;
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
如果你用${}进行传值就是将 ${ } 替换成变量的值。