我对使用感到困惑$ vs #.我没有找到任何指南.我把他们当作
name = #{name},name like '%${word}%',order by name ${orderAs},where name = #{word}
有时,这些都是做工精细,但在有些时候,参数不包括或给我的错误,如
org.apache.ibatis.reflection.ReflectionException:名为'name'的属性没有getter .......
那么,我想知道何时使用$或#?
Pau*_*Pau 24
遵循这些myBatis准则#{}在您的sql语句中使用.
如果您查看Mapper XML文件部分中的任何MyBatis参考,它表示明确:
注意参数表示法:
#{id}
否则${}是为了
1-配置属性.
例如:
<properties resource="org/mybatis/example/config.properties">
<property name="username" value="dev_user"/>
<property name="password" value="F2Fa3!33TYyg"/>
</properties>
Run Code Online (Sandbox Code Playgroud)
然后可以使用下一个属性:
<dataSource type="POOLED">
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
Run Code Online (Sandbox Code Playgroud)
2-字符串替换 ${}(参数部分):
默认情况下,使用#{}语法将导致MyBatis生成PreparedStatement属性并根据PreparedStatement参数安全地设置值(例如?).虽然这更安全,更快速且几乎总是首选,但有时您只想将未修改的字符串直接注入SQL语句.例如,对于ORDER BY,您可以使用以下内容:
ORDER BY $ {columnName}
这里MyBatis不会修改或转义字符串.
注意接受来自用户的输入并以这种方式将其提供给未经修改的语句是不安全的.这会导致潜在的SQL注入攻击,因此您应该禁止在这些字段中输入用户,或者始终执行自己的转义和检查.
所以,在明确name like '%${word}%' or按名称顺序$ {orderAs}`你需要使用字符串替换没有一份准备好的声明.
Ond*_*řej 14
这(${} - 简单变量)
SELECT * from user where usernum = ${usernum}
Run Code Online (Sandbox Code Playgroud)
翻译成这样
SELECT * from user where usernum = 666
Run Code Online (Sandbox Code Playgroud)
,但是这个(#{} - 相当于 JDBC 中的PreparedStatement)
SELECT * from user where usernum = #{usernum}
Run Code Online (Sandbox Code Playgroud)
翻译成
SELECT * from user where usernum = ?
Run Code Online (Sandbox Code Playgroud)
,所以最好的用法是这样的
SELECT * from ${tablename} where name = #{name}
Run Code Online (Sandbox Code Playgroud)