Difference between # and $ in mybatis
1. # Treat all the incoming data as a string, and add double quotes to the automatically incoming data. For example: order by #user_id#, if the value passed in is 111, then the value when parsing into sql is order by "111". If the value passed in is id, the parsed into sql is order by "id".
2. $Displays the passed data directly and generates 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 into sql is order by id.
3. The # method can greatly prevent SQL injection.
4. The $ method cannot prevent Sql injection.
5. The $ method is generally used to pass in database objects, such as passing in table names.
6. Generally, if you can use #, don’t use $.
Prevent Sql injection
Note: Do not write SQL statements as select * from t_stu where s_name like '%$name$%', which is extremely vulnerable to injection attacks.
Parameters in the format "${xxx}" will directly participate in SQL compilation, thus preventing injection attacks. However, when it comes to dynamic table names and column names, you can only use parameter formats like "${xxx}".
When writing mybatis mapping statements, try to use the format "#{xxx}". If you have to use parameters like "${xxx}", you must manually do a good job of filtering 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, but there is nothing wrong with it. If you think it's troublesome to encapsulate the judgment null and '%' into one method.
if (!StringUtil.isEmpty(this.companyName)) { table.setCompanyName("%" + this.companyName + "%"); }The above is the brief discussion on the difference between # and $ in mybatis and the method to prevent SQL injection. I hope everyone will support Wulin.com more~