On the difference between # and $in mybatis from the distribution of Indian troops

In the process of using mybatis, you may write your own SQL statements, and you need to pass parameters to the SQL statements.

But in mybatis, there are two kinds of syntax for passing parameters, #{name} and ${name}. What's the difference between the two? Let's have a look.

for instance

Recently, India is arrogant and frequently provokes border conflicts. Is India so confident?

Let's look at the distribution of Indian forces:

In fact, the Indian army is still very strong. It is the top military power in South Asia. He has the third largest active army in the world, and his army is the second largest in the world.

India is the world's largest arms importer. Of course, there are advantages and disadvantages in importing. The disadvantage is that its own weapons R & D strength is not strong. Of course, India is one of the few countries in the world that possesses nuclear weapons.

Query example

Well, with India's force distribution table, how can we write SQL statements in mybatis to query India's force distribution by number?

  <select id="getIndiaTroopsById" resultType="com.flydean.IndiaTroop">
    select * from troops t
    where  t.id =#{id}
  </select>

We usually write query SQL statements like the above.

Above, we used #{id} as the passed parameter. So #{id} what are the characteristics?

#Characteristics of {ID}

First, #{id} indicates that the passed ID is in string format. For example, if the passed id = 2, the SQL statement will be parsed as:

select * from troops t where t.id = '2'

Secondly, #{id} it will be precompiled, that is, the above SQL statement will be dynamically resolved into a parameter marker?:

select * from troops t where t.id = ?

Parameter replacement is then performed. What are the benefits of precompiling?

The advantage of precompiling is that it can prevent SQL injection.

Characteristics of ${ID}

First of all, ${ID} will not be precompiled and will be replaced with whatever is passed in. So there is a danger of SQL injection.

As in the above example, if we use ${ID}:

  <select id="getIndiaTroopsById" resultType="com.flydean.IndiaTroop">
    select * from troops t
    where  t.id =${id}
  </select>

If we pass in parameter 2, the corresponding SQL statement is:

select * from troops t where t.id = 2

Second, ${ID} is compiled after the value is taken, which cannot prevent SQL injection.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>