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

Posted Beyond meat

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了The difference between "#" and "$" in MyBatis _mybatis相关的知识,希望对你有一定的参考价值。

"#"和“$”二者有何不同呢?动态语句是Mybatis的主要特点。在被定义进mapper里的参数被传递给XML后,Mybatis在查询前会动态地被解析。Mybatis 有两种语法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; 

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

以上是关于The difference between "#" and "$" in MyBatis _mybatis的主要内容,如果未能解决你的问题,请参考以下文章

The difference between variance and bias

What are the differences between Perl, Python, AWK and sed

What are the differences between Perl, Python, AWK and sed

The difference between UDS on IP and UDS on CAN

What is the difference between btree and rtree indexing?

[Immutable.js] Differences between the Immutable.js Map() and List()