When to use $ vs #?

2019-02-01 23:24发布

问题:

I am confused about using $ vs #. I didn't found any guides for this. I used them as
name = #{name}, name like '%${word}%', order by name ${orderAs},where name = #{word}
Sometimes , these are work fine but at the sometimes , parameters aren't included or gave me error like

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

So, I'd like to know when to use $ or # ?

回答1:

Following the myBatis guidelines #{} is used in your sql statements.

If you take a look any of MyBatis Reference in the Section Mapper XML Files it says explicity:

Notice the parameter notation:

#{id}

Otherwise ${} is for

1- Configuration properties.

For example:

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

Then the properties can be used like next:

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

2- String Substitution ${} (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.

So definitively in name like '%${word}%' ororder by name ${orderAs}` you need to use String substitution not a prepared statement.