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]
- <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. ${}