MyBatis of variable references in mapper file #{} vs. ${}

Source: Internet
Author: User

MyBatis of variable references in mapper file #{} vs. ${}

The differences between #{}, and ${} parameters are as follows:
Using the # Pass-through parameter is, SQL statement parsing is added "", as a string to parse, so the advantage compared to $ is more obvious right, #{} parameter can prevent SQL injection, if you pass in the parameter is single quote ', then if you use ${}, this way will be error
Another scenario is if you want to do a dynamic sort, such as an order by column, this time be sure to use ${}
SELECT * FROM table order BY ' name ', this is useless
At the moment, you can use # instead of $,

By default, using the #{} syntax, MyBatis produces preparedstatement statements, and safe settings PreparedStatement parameters, which mybatis perform the necessary security checks and escapes.
Example 1:
Execute Sql:select * from emp WHERE name = #{employeename}
Parameter: Employeename=>smith
Parsed after executing sql:select * from emp where name =?
Execute Sql:select * from emp WHERE name = ${employeename}
Parameter: EmployeeName The incoming value is: Smith
Sql:select executed after parsing * from EMP where name =smith

In summary, the ${} approach raises the issue of SQL injection, and it also affects the precompilation of SQL statements, so do not use ${if you can use #{} from a security and performance standpoint.

But under what circumstances should ${} be used?

Sometimes you may need to insert a string that does not make any modifications to the SQL statement directly. The ${} syntax should be used at this time.

For example, a field name in dynamic SQL, such as: ORDER by ${columnname}

Note: When using the ${} parameter as the field name or table name, specify StatementType as "STATEMENT", such as:

[HTML]
      1. <select id="querymetalist" resulttype="Map" statementtype="STATEMENT"> SELECT * from emp where name = ${employeename} ORDER by ${columnname}</select>

MyBatis of variable references in mapper file #{} vs. ${}

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.