何时使用$ vs#? [英] When to use $ vs #?

查看:74
本文介绍了何时使用$ vs#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用$ vs #感到困惑.我没有找到任何指导.我把它们用作
name = #{name}name like '%${word}%'order by name ${orderAs}where name = #{word}
有时,这些方法可以正常工作,但有时不包含参数,或者给我类似

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:没有吸气剂 对于名为名称"的属性.......

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

所以,我想知道何时使用$#吗?

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

推荐答案

在SQL语句中使用myBatis准则#{}.

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

如果您在地图XML文件明确显示:

注意参数符号:

Notice the parameter notation:

#{id}

否则${}用于

1-配置属性.

例如:

<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-字符串替换${}(参数"部分 ):

2- String Substitution ${} (Parameters section):

默认情况下,使用#{}语法将导致MyBatis生成 PreparedStatement属性,并针对 PreparedStatement参数(例如?).虽然这样更安全,更快, 几乎总是首选,有时您只想直接注入 未修改到SQL语句中的字符串.例如,对于ORDER BY, 您可能会使用以下内容:

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:

按$ {columnName}排序

ORDER BY ${columnName}

MyBatis不会修改或转义字符串.

Here MyBatis won't modify or escape the string.

注意接受用户的输入并将其提供给用户并不安全. 以这种方式未修改的语句.这导致潜在的SQL 注入攻击,因此您应该禁止用户输入 在这些字段中,或者始终执行自己的转义和检查.

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.

因此,按名称$ {orderAs}`的顺序在name like '%${word}%' or中,您需要使用字符串替换而不是准备好的语句.

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

这篇关于何时使用$ vs#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆