I'm going through Hibernate and I know that you can prevent SQL injection with HQL:
String query1 = "from Obj where id = "+ id;
String query2 = "from Obj where id = :id";
query1 is unsafe while query2 is safe.
How can I achieve safe queries with Criteria? Is this already implemented or do I have to do something else?
Criteria c = session.createCriteria(Obj.class);
c.add(Restrictions.eq("id", 5));
I'm going through Hibernate and I know that you can prevent SQL injection with HQL:
It is a very common misconception that ORM solutions, like hibernate, are SQL Injection proof. Hibernate allows the use of "native SQL" and defines a proprietary query language, named, HQL (Hibernate Query Language); the former is prone to SQL Injection and the later is prone to HQL (or ORM) injection. Source: http://software-security.sans.org/developer-how-to/fix-sql-injection-in-java-hibernate
How can I achieve safe queries with Criteria?
As far as your latter question is concerned, Criteria API (similar to PreparedStatement) escapes the parameters and won't cause malicious SQL to be executed.
The bottom line is don't concatenate your application's parameters directly into your query (and make use of Criteria, PreparedStatement), your app is safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With