A fan who has been working for 2 years was asked a basic question in Mybatis.

He ran over to tease me and said, Mr. Mic, if you can answer this question to a certain level, please invite me and a month of milk tea.

The question is: "What is the difference between #{} and ${} in Mybatis"

Let's take a look at the answers of ordinary people and experts to this question.

Ordinary people:

The difference between #{} and ${} in Mybatis:

${} is a dynamic replacement.

{} is a kind of placeholder.

Expert:

OK, I will answer this question in several ways.

First of all, the # and $ placeholders provided by Mybatis are a way to implement dynamic SQL. After passing parameters to XML in these two ways,

Before executing the operation, Mybatis will dynamically resolve these two placeholders.

No. placeholder, equivalent to the one in jdbc? number placeholder.

It is equivalent to setting parameters to the prepared statement in PreparedStatement,

The SQL statement in PreparedStatement is precompiled, and placeholders are used in the SQL statement to specify the structure of the SQL statement.

And when setting parameters, if there are special characters, they will be automatically escaped.

So the # sign placeholder prevents SQL injection.

carbon-202204221206001

Using $ to pass parameters is equivalent to directly splicing the parameters into the original SQL, and Mybatis will not treat it specially.

carbon-202204221206002

Therefore, the biggest difference between $ and # is that the former is a dynamic parameter, and the latter is a placeholder. Dynamic parameters cannot prevent the problem of SQL injection, so in practical applications, the # placeholder should be used as much as possible.

In addition, the dynamic parameter transfer of the $ symbol can be suitable for some dynamic SQL scenarios, such as dynamically passing table names, dynamically setting sorting fields, and so on.

The above is my understanding of the problem.

Summarize

Some small details can cause huge economic losses if not paid attention to.

For example, there are still some websites where SQL injection leads to information leakage.

If you have any interview questions, career development questions, or study questions, you can PM me.

file

Copyright notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated. Reprint please indicate the source Mic带你学架构 !
If this article is helpful to you, please help to follow and like, your persistence is the driving force for my continuous creation. Welcome to follow the WeChat public account of the same name to get more technical dry goods!

跟着Mic学架构
810 声望1.1k 粉丝

《Spring Cloud Alibaba 微服务原理与实战》、《Java并发编程深度理解及实战》作者。 咕泡教育联合创始人,12年开发架构经验,对分布式微服务、高并发领域有非常丰富的实战经验。