hibernate - 在 Hibernate 中防止 SQL 注入(inject)

标签 hibernate hql sql-injection parameterized

我已经使用hibernate与我的数据库进行交互,现在我想让我的数据库层对SQL注入(inject)安全,所以我做了一些研究,我发现我的查询应该是参数化的,这是否意味着我只是构建我的HQL查询作为:

List mothers = session.createQuery(
"select mother from Cat as cat join cat.mother as mother where cat.name = ?")
.setString(0, name)
.list();

然后它被参数化并受到 SQL 注入(inject)的保护,或者还有其他我需要做的事情......

还提到了另一件事-“ 始终逃避您的数据”如何实现?

最佳答案

我不知道 setString()但如果它与 setParameter() 相同那么是的,这样做足以防止sql注入(inject)。

更新

通过转义数据,意味着您必须确保您没有在数据库中存储危险值。

例如,如果您传入参数

String name = "<script>alert('Hello');</script>";
//insert this name into Mother, and then when you load it from the database, it will be displayed    

List mothers = session.createQuery(
"select mother from Cat as cat join cat.mother as mother where cat.name = ?")
.setString(0, name)
.list();

到您的查询,然后下次从数据库中加载它并在您的网络浏览器中呈现它时,它将运行脚本。
您需要确保您的框架转义所有非法字符,即:更改 <&lt;在将其插入数据库之前。
如果您的框架不这样做,则必须手动进行。
有大量的库可以为您正确转义代码。看看this question例如和那里的答案。

关于hibernate - 在 Hibernate 中防止 SQL 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4606505/

相关文章:

Java 程序在 eclipse 中运行但不在命令提示符中

hadoop - 使用配置单元在大范围分区中选择数据

codeigniter - CodeIgniter 会自动防止 SQL 注入(inject)吗?

php - is_numeric() 是否意味着 var 对 MySQL 是安全的?

mysql - 无法设置 Hibernate + Spring + mysql + maven

java - 如何从 configuration.buildSessionFactory (PSQL) 捕获密码错误?

hibernate - JPA2.0/hibernate : Why JPA fires query to update all columns value even some states of managed beans are changed?

hibernate - Sql到Hql的转换

hibernate - 在 Grails 中使用 Hibernate HQL 命名查询?

php - 这个 PHP 函数可以防止 SQL 注入(inject)吗?