使用Hibernate防止SQL注入 [英] SQL injection prevention with hibernate

查看:128
本文介绍了使用Hibernate防止SQL注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有代码,其中应用程序根据许多条件生成不同的sql并通过休眠会话createSQLQuery()执行它们.在这里,这些参数与驻留在java类中的sql字符串相连接,作为常规字符串替换.现在的问题是,我需要防止sql注入.因此,为此,我必须使用getNamedQuery()并绑定参数,以便休眠将处理特殊字符.但是问题在于将字符串sql的字符串移动到xml文件是一项开销,因为有条件地生成sql的字符串.因此,我决定手动进行特殊字符验证,并将其附加到字符串查询中,然后按原样执行. 因此,然后我检查发现的PrepareStatement的来源,它只是抛出异常

I have a existing code where the application generates different sql depend of lot of conditions and execute them via hibernate sessions createSQLQuery(). In here the parameters are concat to the sql string which reside in the java class as normal string replacement. The problem here is now i need to prevent sql injections. So for that i have to use getNamedQuery() and bind the parameters so hibernate will take care of special characters. But the problem is moving the string sql's to xml file is a overhead because conditionally generating sql's. So i decide to manually do the special character validation and append it to the string query and execute as it is now. So then i check the source for PrepareStatement i found, it just throw a exception

byte[] arrayOfByte1 = new byte[0];
try
{
   arrayOfByte1 = CharsToBytes(this.OdbcApi.charSet, arrayOfChar);
}
   catch (UnsupportedEncodingException localUnsupportedEncodingException) {
}

在将参数与字符串查询并置以消除SQL注入之前,如何在上述参数的Java类中进行相同类型的编码?还是有什么办法让我仍然保留字符串sql,因为它是一个附加参数并使用hibernate执行查询?

How can i do same kind of encoding in the java class as above for the parameters before concat them with the string query for eliminate sql injections? Or is there any way i can still keep the string sql as it is an append parameters and use hibernate to execute the query?

推荐答案

据我所知,您想即时创建SQL查询,因为条件的组合(我想是来自UI)可能非常复杂.没关系.您需要控制的只是用户提供的参数.为此,您可以而且应该仍然使用Hibernate的createSqlQuery().该函数可以了解?的位置参数(从查询字符串的开头编号)或:param_name语法,然后提供命名参数.您无需将任何内容移动到xml文件中.

As far as I can tell, you want to create SQL queries on the fly because the combination of conditions (from the UI, I guess) can be very complicated. That's fine. All you need to control are the parameters that the user supplies. And for that, you can, and should, still use Hibernate's createSqlQuery(). That function understands either ? for positional parameters (numbered from beginning of query string), or :param_name syntax and then you supply named parameters. You don't need to move anything into an xml file.

第16.1.7节有示例.

这篇关于使用Hibernate防止SQL注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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