The difference between #{} and ${} in mybatis and fuzzy query

Dynamic SQL is one of the main features of MyBatis. After the parameters defined in the mapper are passed to the xml, MyBatis will dynamically parse them before querying. MyBatis provides us with two syntaxes that support dynamic sql: #{} and ${}.

The difference between #{} and ${}

(1) #{} is pre-compilation processing and dynamic analysis will add double quotation marks to the incoming variable, $ {} is string replacement without double quotation marks.

(2) When MyBatis processes #{}, it replaces #{} in SQL with the? Sign and uses the set method of PreparedStatement to assign the value; when MyBatis processes $ {}, it replaces ${} with the variable value .

(3) Using #{} can effectively prevent SQL injection and improve system security.

(4) Use the pre-compilation mechanism of Preparedstatement. Pre-compilation is to pre-compile the SQL statement in advance, and the parameters injected thereafter will not be SQL-compiled. The pre-compilation mechanism can prevent SQL injection very well. In some special occasions, only ${} can be used, not #{}. For example: ORDER BY ${id} when sorting is used, if #{id} is used, it will be parsed into ORDER BY "id", which is obviously a wrong way of writing.


<select id="selectUser" parameterType="int" resultType="user">
  SELECT id,name,password FROM user WHERE password = #{password}
</select>

If the incoming password is 123456, it will be parsed into SELECT id,name,password FROM user WHERE password = "123456" (with double quotes) during parsing

<select id="selectUser" parameterType="int" resultType="user">
  SELECT id,name,password FROM user WHERE password = ${password}
</select>

If the incoming password is 123456, it will be parsed into SELECT id, name, password FROM user WHERE password = 123456 (without double quotes) during parsing

Fuzzy query using mybatis in mysql

Never write

<select id="selectUser" parameterType="int" resultType="user">
  SELECT id,name,password FROM user WHERE name LIKE "%#{password}%" 
</select>

Because the sql that the database gets after the dynamic analysis is SELECT id, name, password FROM user WHERE name LIKE "%"小"%", there is no doubt that such SQL statements are definitely wrong.

This is the correct way of writing:

<select id="selectUser" parameterType="int" resultType="user">
  SELECT id,name,password FROM user WHERE name LIKE concat("%",${password},"%") 
</select>

If the incoming name is small , after dynamic resolution becomes SELECT id, name, password FROM user WHERE name LIKE "% small%", the name of the database will be included little information check out

concat function

CONCAT(String 1, String 2, String 3, …): Concatenate string 1, string 2, string 3, etc. together.

Reference article: https://www.cnblogs.com/liaowenhui/p/12217959.html

Guess you like

Origin blog.csdn.net/qq1350975694/article/details/107758152
Recommended