Java Reference
In-Depth Information
Criteria crit = session.createCriteria(Product.class);
Criterion price = Restrictions.gt("price",new Double(25.0));
Criterion name = Restrictions.like("name","Mou%");
LogicalExpression orExp = Restrictions.or(price,name);
crit.add(orExp);
crit.add(Restrictions.ilike("description","blocks%"));
List results = crit.list();
The equivalent HQL would be the following:
from Product where price > 25.0 and name like 'Mou%'
We would have to wrap that HQL in a couple of lines of Java code, but even so, we find this
particular example to be clearer in HQL. In the previous HQL example, you can see that we
used the where clause with a > (greater than) comparison operator, an and logical operator, and
a like comparison operator. You do have to enclose literal strings in quotes in HQL. To find
names that have the literal Mou at the beginning of the string, we used % in the query.
Using Named Parameters
Hibernate supports named parameters in its HQL queries. This makes writing queries that
accept input from the user easy—and you do not have to defend against SQL injection attacks.
n Note SQL injection is an attack against applications that create SQL directly from user input with string
concatenation. For instance, if we accept a name from the user through a web application form, then it
would be very bad form to construct an SQL (or HQL) query like this:
String sql = "select p from products where name = '" + name + "'";
A malicious user could pass a name to the application that contained a terminating quote and semicolon, fol-
lowed by another SQL command (such as delete from products ) that would let them do whatever they
wanted. They would just need to end with another command that matched the SQL statement's ending quote.
This is a very common attack, especially if the malicious user can guess details of your database structure.
You could escape the user's input yourself for every query, but it is much less of a security
risk if you let Hibernate manage all of your input with named parameters. Hibernate's named
parameters are similar to the JDBC query parameters ( ? ) you may already be familiar with, but
Hibernate's parameters are less confusing. It is also more straightforward to use Hibernate's
named parameters if you have a query that uses the same parameter in multiple places.
When you use JDBC query parameters, any time you add, change, or delete parts of the
SQL statement, you need to update your Java code that sets its parameters, because the
parameters are indexed based on the order they appear in the statement. Hibernate lets you
provide names for the parameters in the HQL query, so you do not have to worry about acci-
dentally moving parameters further up or back in the query.
Search WWH ::




Custom Search