Parameter Binding in HQL

Parameter binding is the process of binding a Java variable with an HQL statement. Using Parameter binding and not string concatenation for HQL statement creation will also guard against attacks like SQL injection. Examples in this article are a continuation of the ones in the article http://www.javajee.com/introduction-to-hibernate-query-language-hqlInstead of hard-cording the values in the HQL statement like "Select id from User where id = 1 ", we can bind a java variable to an HQL statement as:

int idVar=1;

Query query = session.createQuery("Select id from User where id = ?");

query.setInteger(0, idVar);

List<Integer> ids = (List<Integer>) query.list();

  for (int i : ids) {

    System.out.println(i);

    }

You should have this code within a transaction boundary as in the examples at http://www.javajee.com/introduction-to-hibernate-query-language-hql and test it simililarly.

We pass the position of the question mark and the variable name to the query.setXXX (XXX= any type like Integer, Decimal etc.) methods. Here we have only one ‘?’ and its position is 0.  Find another HQL example statement with multiple query parameters:

int idVar = 1;

String namePattern="User%";

Query query = session.createQuery("Select id from User where id > ? and name like ? ");

query.setInteger(0, idVar);

query.setString(1, namePattern);

 

Creating HQL statement through string concatenation and SQL injection risks

You can also create HQL queries like above using String concatenation like  “Select id from User where id = “ + idVar + “and name =”+ namePattern. But this syntax is difficult to maintain and also invite opportunities for SQL injection. We will see SQL injection later, but in summary, it is a process by which user will pass something else in a form parameter and get those record which he is not supposed to get. For instance, assuming if namePattern is taken from user through a form, he can pass “X% or 1=1”.

int idVar = 1;

String namePattern = "'X%' or 1=1";

Query query = session.createQuery("Select id from User where id > " + idVar

    + " and name like " + namePattern);

List<Integer> ids = (List<Integer>) query.list();

Final query created by appending will be "Select id from User where id > 0 and name like 'X%' or 1=1". This will return all the records irrespective of the ids and names as the or condition 1=1 will be always true.

Above situation will not happen in the case of parameter binding, as HQL creates the final HQL statement in such a way that the whole of namePattern is compared with the name field alone and not just appended to the HQL statement.  Now try passing the same idVar and namePattern variables to the HQL statement using parameter binding:

int idVar = 1;

String namePattern="'X%' or 1=1";

Query query = session.createQuery("Select id from User where id > ? and name like ?");

query.setInteger(0, idVar);

query.setString(1, namePattern);

List<Integer> ids = (List<Integer>) query.list();

 

Named Parameters

We can use named placeholders in the HQL statement rather than using question marks (?) and avoid the need to remember the positions of each question marks (?) for binding variables;

int idVar = 1;

String namePattern="U%";

Query query = session.createQuery("Select id from User where id > :idVarHolder and name like :namePatternHolder");

query.setInteger("idVarHolder", idVar);

query.setString("namePatternHolder", namePattern);

List<Integer> ids = (List<Integer>) query.list();

You define a named placeholder by writing the placeholder name after a colon (:) as :holdername and use it within a setXXX method without the colon (:) as “holdername”. 

 

Tags: 

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)