The difference between # and $ in mybatis
1. #Treat the incoming data as a string, and add a double quotation mark to the automatically incoming data. For example: order by #user_id#, if the value passed in is 111, then the value when parsed into sql is order by "111". If the value passed in is id, the parsed sql is order by "id".
2. $ Display the incoming data directly and generate it in sql. For example: order by $user_id$, if the value passed in is 111, then the value when parsed into sql is order by user_id. If the value passed in is id, the parsed sql is order by id.
3. #Method can prevent sql injection to a great extent.
4.$ method cannot prevent Sql injection.
5. The $ method is generally used to pass in database objects, such as table names.
6. If you can generally use #, don’t use $.
Prevent Sql injection
Note: Do not write the SQL statement as select * from t_stu where s_name like '%$name$%', which is extremely vulnerable to injection attacks.
Parameters in the format of "${xxx}" will directly participate in sql compilation, so injection attacks cannot be avoided. But when it comes to dynamic table names and column names, only parameter formats such as "${xxx}" can be used.
When writing the mapping statement of mybatis, try to use the format of "#{xxx}". If you have to use parameters such as "${xxx}", you must manually filter them to prevent SQL injection attacks.
Example
<sql id="condition_where"> <isNotEmpty property="companyName" prepend=" and "> t1.company_name like #companyName# </isNotEmpty> </sql>
The java code is similar to your original one, and there is nothing wrong with it. If you find it troublesome, set the judgment to null and '%' can be encapsulated into a method
if (!StringUtil.isEmpty(this.companyName)) { table.setCompanyName("%" + this.companyName + "%"); }
The above is a brief discussion of # and in mybatis brought to you by the editor The difference between $ and the method to prevent sql injection is all covered. I hope everyone will support the PHP Chinese website~
For more about the difference between # and $ in mybatis and the method to prevent sql injection, please pay attention to PHP for related articles Chinese website!