Fork me on GitHub

The difference between "#" and "$" in MyBatis _mybatis

"#"和“$”二者有何不同呢?动态语句是Mybatis的主要特点。在被定义进mapper里的参数被传递给XML后,Mybatis Dynamic SQL在查询前会动态地被解析。Mybatis 有两种语法:#{} and ${}。

简而言之,'#{}' 被解析成placeholder '?',‘${}’被解析成字符串。因为${}的SQL injection问题,我们一般优先使用‘#{}’。


 

Dynamic SQL is one of the main features of MyBatis, and after the parameters defined in mapper are passed into the XML, MyBatis is dynamically parsed before the query. MyBatis provides us with two syntax to support dynamic SQL: '#{}' and '${}'.

 

In the following statement, if the value of username is Mike, there is no difference between the two ways:

SELECT * from user where name = #{name};
SELECT * from user where name = ${name};

After parsing, the results are

SELECT * from user where name = ' Mike';

However, '#{}' and '${}' are not handled in the precompilation. When '#{}' is preprocessing, the parameter part is used as a placeholder '?' Instead, it becomes the following SQL statement:

SELECT * from user where name =?;

The '${}' is simply a string replacement, which in the dynamic parsing phase is parsed into

SELECT * from user where name = ' Mike';

Above, the parameter substitution of ‘#{}’ occurs in the DBMS(data base management system), and ‘${}’ occurs in the dynamic parsing process.

So, which way should we use in the process?

The answer is, prioritize the use of #{}. Because ${} can cause problems with SQL injection. Look at the following example:

SELECT * from ${tablename} where name = #{name}

In this example, if the table is named

User Delete user; --

After dynamic parsing, SQL is as follows:

select * from user; Delete user; --WHERE name =?;

-After the statement is commented out, and the original query user's statement into the query all user information and DELETE user table statements, will cause significant damage to the database, which may cause server downtime.

 

But the table name is passed in with the parameter, can only use ${}, the concrete reason may make a guess by oneself, to verify. This also reminds us of the problem of SQL injection being careful in this usage.

posted @ 2022-02-12 09:42  z_s_s  阅读(65)  评论(0)    收藏  举报