When to use $ vs #?

前端 未结 1 1123
清酒与你
清酒与你 2020-12-08 05:24

I am confused about using $ vs #. I didn\'t found any guides for this. I used them as
name = #{name}, name like \'%${word}%\',

相关标签:
1条回答
  • 2020-12-08 05:43

    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.

    0 讨论(0)
提交回复
热议问题