何时使用 $ 与 #?

When to use $ vs #?

我对使用 $ vs # 感到困惑。我没有找到任何指南。我将它们用作
name = #{name}name like '%${word}%'order by name ${orderAs}where name = #{word}
有时,这些工作正常,但有时,不包括参数或给我错误,如

org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'name'.......

所以,我想知道什么时候使用 $#

遵循 myBatis 准则 #{} 用于您的 sql 语句中。

如果你看一下 Mapper XML Files 节中的任何 MyBatis 参考资料,它会明确说明:

Notice the parameter notation:

#{id}

否则 ${} 用于

1- 配置 properties

例如:

<properties resource="org/mybatis/example/config.properties">
  <property name="username" value="dev_user"/>
  <property name="password" value="F2Fa3!33TYyg"/>
</properties>

然后属性可以像下面这样使用:

<dataSource type="POOLED">
  <property name="username" value="${username}"/>
  <property name="password" value="${password}"/>
</dataSource>

2- 字符串替换 ${} (Parameters section):

By default, using the #{} syntax will cause MyBatis to generate PreparedStatement properties and set the values safely against the PreparedStatement parameters (e.g. ?). While this is safer, faster and almost always preferred, sometimes you just want to directly inject a string unmodified into the SQL Statement. For example, for ORDER BY, you might use something like this:

ORDER BY ${columnName}

Here MyBatis won't modify or escape the string.

NOTE It's not safe to accept input from a user and supply it to a statement unmodified in this way. This leads to potential SQL Injection attacks and therefore you should either disallow user input in these fields, or always perform your own escapes and checks.

所以在 name like '%${word}%' ororder by name ${orderAs}` 中,您需要使用字符串替换而不是准备好的语句。

这个(${} - 简单变量)

SELECT * from user where usernum = ${usernum}

翻译成这个

SELECT * from user where usernum = 666

,但是 (#{} - 相当于 JDBC 中的 PreparedStatement)

SELECT * from user where usernum = #{usernum}

转换为

SELECT * from user where usernum = ?

,所以最好的用法是

SELECT * from ${tablename} where name = #{name}

我也被这个搞糊涂了。然后我做了一些研究。我在 ibatis 中有一个类似于 select * from tablename h where h.id=#userid# 的查询。然后我不得不将它迁移到 mybatis 3 中。同样的声明没有奏效。所以我把它改成 select * from tablename h where h.id=#{userid}