What is the difference between $ and # in mybatis? why?

1. There are two ways to pass parameterType to the SQL statement in the Mapper.xml statement of Mybatis: # {} and $ {}
We often use # {}, because this way can prevent SQL injection, # {} this In this way, the SQL statement is pre-compiled, and it escapes the parameter in the middle of # {} into a string.
For example:
select * from table where name = # {zhangSan} After
pre-compilation, it will be dynamically parsed into a parameter marker ?:
select * from table where name =?
While using $ {} during dynamic resolution, parameter characters will be passed in String
select * from table where name = $ {zhangSan} 
dynamic parsing, the parameter string will be passed in
select * from table where name = 'zhangSan'
Summary:
# {} This value is the value of the compiled SQL statement and then the value is # {}: dynamic analysis-> pre-compilation-> execute
$ {} This is the value and then compile the SQL statement that is $ {}: Dynamic analysis-> compile-> execute
#The incoming parameter is displayed as a string (as a string) in SQL, and double quotes will be added to the automatically incoming data.
$ Incoming parameters are directly displayed as incoming values ​​in SqL
The $ {} variable substitution phase is in the dynamic SQL parsing phase, and # {} variable substitution is in the DBMS.
 

2. # can prevent the risk of SQL injection (splicing of statements); but $ cannot prevent Sql injection.

3. The $ method is generally used to transfer database objects, such as the table name.

4. In most cases, # is still often used. Generally, if you can use #, don't use $; but in some cases, you must use $.

Guess you like

Origin www.cnblogs.com/cdlyy/p/12749199.html