What's the difference between # {} and ${} in MyBatis
This article mainly introduces the difference between # {} and ${} in MyBatis, which has a certain reference value. Interested friends can refer to it. I hope you can learn a lot after reading this article.
Preface
In the mapping configuration file of MyBatis, there are two ways to pass parameters dynamically:
1. # {} placeholder
2. ${} splicer
# {} and ${}
Difference 1
# {} is the parameter placeholder?, that is, sql precompilation
${} is string substitution, that is, sql stitching
Difference 2.
# {}: dynamic parsing-> precompilation-> execution
${}: dynamic parse-> compile-> execute
Difference 3.
The variable substitution of # {} is in DBMS
The variable substitution of ${} is outside of DBMS
Difference 4.
After variable replacement, the variable corresponding to # {} is automatically enclosed in single quotation marks''
After variable replacement, the variable corresponding to ${} will not be enclosed in single quotation marks''
Difference 5.
# {} prevents sql injection
${} cannot prevent sql injection
# {} and ${} instances: suppose the passed parameter is 1 instance step 1 # {}: select * from t_user where uid=# {uid} ${}: select * from t_user where uid='${uid} 'instance step 2 # {}: select * from t_user where uid=? ${}: select * from t_user where uid=' 1' instance step 3 # {}: select * from t_user where uid='1 instance ${}: select * from Values in curly braces of t_user where uid='1s # {} and ${}
The case of a single parameter
# {}
${}
Case of multiple parameters # {}
${}
# {} and ${} tips and suggestions in use
1. Whether it is a single parameter or multiple parameters, the annotation @ Param (") is recommended.
2. Use # {} where you can, and use ${} less or less
3. When the table name is used as a parameter, you must use ${}. Such as: select * from ${tableName}
4. When order by, you must use ${}. Such as: select * from t_user order by ${columnName}
5. If you use # {} in the name of the list, you will directly report an error; sorting with # {} after order by will not take effect.
6. When using ${}, pay attention to when to add or not add single quotation marks, that is, ${} and'${}'. In general, single quotation marks are required when the field type is char or varchar
Thank you for reading this article carefully. I hope the article "what's the difference between # {} and ${} in MyBatis" shared by the editor is helpful to you. At the same time, I also hope you can support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!