On the difference between # and $in mybatis and the methods to prevent SQL injection
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, the value parsed into SQL is order by "111". If the value passed in is ID, the value parsed into SQL is order by "Id" 2. $ The incoming data is directly displayed and generated in SQL. For example, order by $user_ ID $. If the value passed in is 111, the value when parsing into SQL is order by user_ ID. if the value passed in is ID, the SQL parsed is order by ID. 3# This method can prevent SQL injection to a great extent. 4.$ This method cannot prevent SQL injection.
5. The $method is generally used to pass in database objects, such as table names 6. Generally, # don't use $
Prevent SQL injection
Note: the SQL statement should not be written as select * from t_ stu where s_ Name like '% $name $%', which is vulnerable to injection attacks.
”Parameters in the form of ${XXX} "will directly participate in SQL compilation, so injection attacks cannot be avoided. However, when dynamic table names and column names are involved, 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 should filter manually to prevent SQL injection attacks.
example
The Java code is almost the same as your original one. In fact, there is nothing wrong. If you feel troublesome, just wrap the judgment null and '%' into one method
The above is all about the differences between # and $in mybatis and the methods to prevent SQL injection. I hope you can support programming tips~