Use ${} and #{} in Mybatis

#{}: 1. The parameter passed in is displayed as a string in SQL. 2. The method can largely prevent sql injection

${}: 1. The parameter passed in is directly displayed as the value passed in in sql. 2. The method cannot prevent Sql injection.

1. Use #{}

When Mybatis preprocesses #{}, it will process #{} as a placeholder, and the parameters will be replaced when it is actually executed, which is equivalent to jdbc's PreparedStatement.

<select id="select" parameterType="java.lang.String" resultType="baseMap">
    select * from user where name = #{name}
</select>

The actual printed sql of the above configuration is

select * from user where name = ?

This tells MyBatis to create a PreparedStatement parameter. In JDBC, such a parameter will be identified by a "?" in SQL and passed to a new PreparedStatement, like this:

// 近似的 JDBC 代码,非 MyBatis 代码...
String selectPerson = "select * from user where name = ?";
PreparedStatement ps = conn.prepareStatement(selectPerson);
ps.setString(1,name);

This effectively prevents sql injection.

2. Use ${}

<select id="select" parameterType="java.lang.String" resultType="baseMap">
    select * from user where name=${name}
</select>

The actual printed sql of the above configuration is

select * from user where name = name

// 近似的 JDBC 代码,非 MyBatis 代码...
String selectPerson = "SELECT * FROM PERSON WHERE ID=?";
PreparedStatement ps = conn.prepareStatement(selectPerson);
ps.setInt(1,id);

${} is just a simple string replacement. In the dynamic parsing stage, the sql statement will directly replace the variable value, so there may be a risk of sql injection.

3. The difference between $ and #

1. #{} is a placeholder, ${} is just an ordinary pass value

2. When #{} is used, it will choose whether to add double quotes according to the value passed in. Therefore, when we pass parameters, we usually pass them directly without adding double quotes; ${} will not, we need to add them manually

3. When passing a parameter, we can write any value in #{}

4. #{} performs character filtering for SQL injection, while ${} is just used as an ordinary value, and these problems are not considered

5. The application scenario of #{} is to pass the condition to the where clause of the SQL statement; the application scenario of ${} is to pass some values ​​that need to participate in the syntax generation of the SQL statement

 

Guess you like

Origin blog.csdn.net/m0_69804655/article/details/130015134