【the difference】
-
#{ } is precompiled processing, ${ } is string replacement
-
When Mybatis processes #{ }, it will use a placeholder for #{ } in sql to replace the parameter, and then call the set method of PreparedStatement to assign the value.
-
When Mybatis is processing , it is to put { }, it is to put, is to replace { } with the value of the variable.
-
Using #{ } can effectively prevent SQL injection and improve system security.
【scenes to be used】
- In general, #{} is preferred, because it can avoid sql injection; if you need to pass parameters to dynamic table names and dynamic field names, you need to use ${}
- 比如:select * from ${tableName} where id > #{id};
[SQL injection problem]
For example, if you use ${} to inject problems:
select * from ${tableName};
If the parameter t_user;delete from t_user is passed, the precompiled sql is as follows, which will cause the system to be unavailable:
select * from t_user;delete from t_user
[like statement anti-injection]
Use the concat function:
select * from t_user where name like concat('%', #{name}, '%')