The difference between an MyBatis middle and a dollar sign

  • 2020-05-30 20:02:43
  • OfStack

#{variable name} can be precompiled, type matching, etc. #{variable name} will be converted to jdbc type.

select * from tablename where id = #{id}

If the database field id is of character type, then #{id} is '12', if id is of integer type, then id is 12, and MyBatis converts the SQL statement above to select * from tablename where id=? The & # 63; The parameter is set to the value of id.

${variable name} does not match the data type.

select * from tablename where id = ${id}

If the field id is integer, the sql statement will not fail, but if the field id is character, the sql statement should be written

select * from table where id = '${id}'

The # approach greatly prevents sql injection.

$mode cannot be injected with sql.

$1 is generally used to pass in database objects, such as table names.

Use # more and $less.

The mybatis framework is a semi-automated persistence layer framework. We have to write the sql statements by ourselves, so we need to prevent the injection of sql. Actually, sql of Mybatis is a structure with "input + output" function, which is similar to a function, as follows:

select id="getBlogById" resultType="Blog" parameterType= " int " >
select id,title,author,content 
from blog where id=#{id} 

Here, parameterType identifies the input parameter types, and resultType identifies the output parameter types. In response to the above, if we want to prevent sql injection, we naturally have to work on the input parameters. The highlighted part of the above code is the part where the input parameters are spliced in sql. After the parameters are passed in, the sql statement executed is printed, and you will see that sql looks like this:

select id,title,author,content from blog where id = ?

The printed sql looks like this no matter what parameter is entered. This is because mybatis enables precompilation. Before the execution of sql, sql above will be sent to the database for compilation. During the execution, sql will be directly used to replace the placeholder "? ". That's it. Since sql injection only works for the compilation process, this approach nicely avoids the problem of sql injection.

Related articles: