The difference between #{} and ${} in MyBatis, and another problem with ${}

When I didn't use MyBatis before, directly writing JDBC would use Statement and Prepare. PrepareStatement can avoid the SQL injection problem of Statement, and the way ?to avoid it is to use it as a placeholder, where ${} and #{} are similar situations.

Here are two examples for comparison.

对于 select * from user where id=#{
    
    }
传入参数 1001
实际SQL select * from user where id='1001'
    
对于 select * from user where id=${
    
    }
传入参数 1001
实际SQL select * from user where id=1001

As mentioned earlier, we use PrepareStatement to prevent SQL injection, and here we also use #{} to prevent SQL injection.

假如我们在程序中写这样的SQL 
String sql = "select * where name= ' "+name+" ' "
传入参数 name = " 'or 1=1 '"
最终的SQL结果
    select * where name= ' ' or '1=1'

Use ${}:

Insert picture description here

In this way, you can skip the query condition (– is the SQL comment) and get all the results directly. The use of PrepareStatement and #{} can avoid this situation, they will pass the parameter into a string, directly add quotation marks.

use#{}:

Insert picture description here

But if you use order by, like, and the incoming table name, you need to use ${}, because they cannot be enclosed in quotation marks.


The above description is similar to other places on the Internet. The following is another problem I encountered during the test.

When we configure the data source for MyBatis, we either write the driver, url and other parameters directly in the environment tag, or import the configuration in database.properties through the proper tag (you can also write the properties directly in the properties tag)

mybatis-config.xml

Insert picture description here

databse.properties
Insert picture description here

UserMapper.java
Insert picture description here

If we write SQL in UserMapper.xml and the variable name used happens to be username1 or username2, which is the same as the property name in the properties tag, then the first thing obtained through ${username1} is in the properties instead of us The entity class User passed over.
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_39763246/article/details/114653959