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

Source: Internet
Author: User
Tags 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 Zhangsan, 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 = ' Zhangsan ';

However, #{} and ${} are not handled in the precompilation. #{} When 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 = ' Zhangsan ';

Above, the parameter substitution of #{} occurs in the DBMS, 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 + 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.