Talking about the difference between ${ } and #{ } in Mybatis

1. Examples

1 select * from user where name = "dato";
2
3 select * from user where name = #{name};
4
5 select * from user where name = ${name};

Normally, we don't notice any difference here. Because these sql can achieve our purpose, to query the user named dato.

Second, the difference

Dynamic SQL is one of the powerful features of mybatis and an important reason why it is superior to other ORM frameworks. Before precompiling the sql statement, mybatis will dynamically parse the sql and parse it into a BoundSql object, which is also where the dynamic SQL is processed. #{ } and ${ } behave differently during dynamic SQL parsing

select * from user where name = #{name};

When #{} is dynamically parsed, it will be parsed into a parameter marker. That is, the statement after parsing is:

select * from user where name = ?;

 

 

Then when we use ${}

select * from user where name = ${name};

When ${} is dynamically parsed, the parameters we pass in will be filled into our statement as String strings, and it will become the following statement

select * from user where name = "dato";

The SQL statement before precompiling no longer contains variables and is completely constant data. It is equivalent to our ordinary sql without variables.

To sum up, the replacement phase of the ${ } variable is in the dynamic SQL parsing phase, and the replacement of the #{ } variable is in the DBMS.

This is the main difference we can see between #{} and ${}, in addition to the following differences:

  • The # method can largely prevent sql injection.
  • The $ way cannot prevent Sql injection.
  • The $ method is generally used to pass in database objects, such as passing in a table name.
  • Do not use $ if you can use #.

So when we use mybatis, try to use the # method! ! ! This is where everyone should pay attention

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325725647&siteId=291194637