#{ } and ${ } in MyBatis

【the difference】
  1. #{ } is precompiled processing, ${ } is string replacement

  2. 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.

  3. When Mybatis is processing , it is to put { }, it is to put, is to replace { } with the value of the variable.

  4. Using #{ } can effectively prevent SQL injection and improve system security.

【scenes to be used】
  1. 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 ${}
  2. ​ 比如: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}, '%')

Guess you like

Origin blog.csdn.net/Ivy_Xinxxx/article/details/108146543