The difference between dynamic parameter transfer in mybatis ${} and #{}

 

 

Their difference is summarized in one sentence: #{name} puts double quotes on the data, and ${name} directly displays the data.

 

1. #{name} treats the incoming parameter as a string and will be pre-compiled,

Example: select * from a where name = #{name} input parameter name=haha

In fact, it is equivalent to select * from a where name ="haha",

2. ${name} will not be precompiled,

Example: select * from a where name = #{name}, input parameter name= haha,

Actually it is equivalent to select * from a where name = haha,

 

When to use ${} When to use#

 (1) When you enter a parameter and pass it a string, you can use # 

 (2) The input parameter is a value, you can use ${}

 (3) When using order by dynamic parameter when sorting in MyBatis, use $ instead of #

  (4) When dynamically transmitting the table name, use $ instead of # (select * from ${tableName})

Suggestion: The advantage of being able to use #{}Try to use # # is that it can prevent SQL injection to a large extent, while $ cannot

Example: If the front desk query call query a table data sql

mybatis sql: select * from a where name=#{name} and state= #{state}, if the name from the front desk is "haha" and the state field is "0 or state=1", use # to not There will be sql injection, and if it is replaced by the $ method, the sql statement becomes select * from a where name=haha and state= 0 or state=1. In this way, SQL injection is formed.

Guess you like

Origin blog.csdn.net/qq_37557563/article/details/107163315