In this tutorial of SQL Injection and Parameter Binding in Hibernate we will discuss about SQL inject and its demerits and also describe Parameter binding, it means is way to bind parameter with SQL to use in the hibernate for particular criteria.
SQL Injection:
Injection: “SELECT * FROM student WHERE studentName= ” +studentName
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 the former is prone to SQL Injection and the later is prone to HQL injection.
@ImageSource-Slideshare.net
Parameter Binding:
Without parameter binding, you have to concatenate the parameter String like this (bad code) :
String hql = "from Student student where student.studentName = '" + studentName+ "'"; Query query = session.createQuery(hql); List result = query.list();
Hibernate parameter binding
- Named parameters binding
- Positional parameters binding.
Example 1 – setParameter
String hql = "from Student student where student.rollNumber= :rollNumber"; Query query = session.createQuery(hql); query.setParameter("rollNumber", "3"); List result = query.list();
Example 2 – setString
You can use setString to tell Hibernate this parameter date type is String.
String hql = "from Student student where student.studentName= :studentName"; Query query = session.createQuery(hql); query.setString("studentName", "Sweety Rajput"); List result = query.list();
Example 3 – setProperties
Student student= new Student(); student.setCourse("MCA"); String hql = "from Student student where student.course= :course"; Query query = session.createQuery(hql); query .setProperties(student); List result = query.list();
2. Positional parameters
String hql = "from Student student where student.course= ? and student.studentName = ?"; Query query = session.createQuery(hql); query.setString(0, "MCA"); query.setParameter(1, "Dinesh Rajput") List result = query.list();
<<Previous Chapter 27<< >>Next Chapter 29>>
Please give example of using alias in HQL
Thanks Farhan. https://www.dineshonjava.com/introducing-hqlhibernate-query-language/