http://www.developer.com/open/article.php/3322131/Introducing-HQL-The-Object-Oriented-Query-Language-from-Hibernate.htm
In the previous article, we explored Hibernate, a popular Open Source O/R Mapping framework for J2EE-based enterprise applications. Hibernate automates to a large extent the creation of an efficient persistence layer for the enterprise application. Hibernate makes mapping objects to be persisted to underlying database easier. In other words, Hibernate allows representing an underlying database by using simple Java objects and vice versa. By facilitating direct retrieval of persistent objects from the database, Hibernate automates/hides the process of creating objects and populating them with data retrieved from the database (common in JDBC-based applications), saving the developer from such tedious routine tasks. Hibernate uses the following ways to retrieve objects from the database: The most preferred way is using the Hibernate Query Language (HQL), which is an easy-to-learn and powerful query language, designed as a minimal object-oriented extension to SQL. HQL has syntax and keywords/clauses very similar to SQL. It also supports many other SQL-like features, such as aggregate functions (for example: sum(), max()) and clauses such as group by and order by clause. Although it is possible to use native SQL queries directly with a Hibernate-based persistence layer, it is more efficient to use HQL instead. The reasons of choosing HQL over the other two methods are given below: As described earlier, most of HQL's syntax and features are very similar to SQL. An HQL query may consist of following elements: Clauses are HQL keywords that make up queries. The following table contains some important and commonly/often used clauses and their syntax along with their examples. Table A: HQL Clauses with their description, syntax, and examples. Aggregate functions, when used in HQL queries, return an aggregate value (such as sum, average, and count) calculated from property values of all objects satisfying other query criteria. These functions can be used along with the distinct and all options, to return aggregate values calculated from only distinct values and Example: select sum(emp.sal) from comp.Emp as emp Subqueries are queries within queries, surrounded by parentheses (). Subqueries get executed before the main query and are used to provide criteria for grouping/ordering/aggregating or narrowing query result with where clause. It should be noted that HQL queries might contain subqueries only when subqueries are supported by the underlying database. Example: select dept.emp_name from comp.Dept as dept where dept.emp_sal > (select avg(dept.emp_sal) from dept) For more information on HQL elements, refer to Hibernate's Web site. HQL can be used in any one of the following ways in the Hibernate-based persistence layer code of application: Here, the Query object q1 uses the list() method to return a List object containing a list of query results. Alternatively, the same task can be accomplished using the following code: Or simply, First, a Criteria object is obtained by invoking the Session object's createCriteria() method, providing a class of object(s) desired to be returned as a query result, as a method argument. Now, the query criteria can be specified by using various methods of the Criteria object, for instance: Example: These two methods can be used to perform query operations with HQL in the persistence layer code of the application. They also support native SQL queries in place of HQL. This approach helps you to fall back on native SQL in cases where HQL doesn't provide certain features required but are available through native SQL only. Hibernate Query Language (HQL) is a rich and powerful object-oriented query language available with the Hibernate O/R Mapping Framework. This query language, designed as a "minimal object-oriented extension to SQL," allows you to represent SQL queries in object-oriented terms—by using objects and properties of objects. HQL provides many advanced features compared to SQL, yet is easier to learn and use as its syntax and basic features are very similar to SQL. It facilitates writing database-type independent queries that are converted to a local SQL dialect of the underlying database at runtime. Mugdha Chauhan (formerly Mugdha Vairagade) is a senior IT consultant and author. An Open Source supporter, she frequently writes articles and tutorials on useful emerging Open Source projects. Major tech portals including developer.com, IBM developerWorks, CNET Networks, Slashdot, and many eZines regularly publish her work. Her expertise and interests include Java, Linux, XML, wireless application development, and Open Source.
Introducing HQL: The Object-Oriented Query Language from Hibernate
March 5, 2004
Note: The Criteria API also uses HQL behind the scenes.
Why HQL?
HQL Syntax
Clauses
Clause
Description
Syntax
Example from
The simplest form of an HQL query. Specifies the object whose instances are to be returned as the query result. Commonly used with the select clause.
from object [as object_alias]* object_alias simply means another name given to refer to an object for convenience.
from comp.Dept as dept
Will return all instances of object dept.select
Specifies objects and properties to be returned in the query result set. Used in conjunction with the from clause.
select [object.]property
select dept.mgr from comp.Dept as dept
Will return all values of mgr in all instances of dept.where
Specifies the conditions that should be satisfied by the instances returned as the query result. Used with select and/or from clause.
where condition
Here, condition is a combination of logical, relational operators i.e. =, >, AND, NOT etc.select dept.mgr from comp.Dept as dept where dept.emp_no > 10
Will return all instances of mgr in dept whose corresponding emp_no values are greater than 10.order by
Specifies the order (ascending/descending) in which the properties of objects returned as query results should be listed. Used with the select and from clauses.
order by object0.property0 [asc|desc][, object1.property0]...
By default, order is ascending unless specified otherwise.select dept.mgr from comp.Dept as dept order by dept.emp_no asc
Will return a list of all instances of mgr in dept in ascending order of corresponding emp_no values.group by
Specifies the grouping criteria using objects properties, by which the list of objects returned as a query result should be grouped together. Used with the select and/or from clause.
group by object0.property0[, object1.property0]...
select dept.emp_no from comp.Dept as dept group by dept.mgr
Will return list of all emp_no instances from dept grouped by corresponding values of mgr.
Legend: Bold: keywords/clauses
Italics: variables [...]: Optional
a | b: either a or b Aggregate Functions
Subqueries
Note: HQL queries, except classnames and variables used in them, are case-insensitive. In other words, select is same as SELECT or even select; although it is a general practice to write HQL queries in lowercase for the sake of better readability.
HQL at Work
First, instantiate the Session object using the openSession() method of SessionFactory.
Then, invoke the createQuery() method on the resulting object.
Example:
Session session;
Query q1 = session.createQuery("select emp.sal
from comp.Emp as emp");
List result = q1.list();
List result = session.createQuery("select emp.sal
from comp.Emp
as emp").list();
session.createQuery("select emp.sal from comp.Emp
as emp").list();
Note: The Query object also consists of similar query criteria-specifying methods, such as Criteria, that can be used make the query code look clean and less verbose.
Session session;
//some code
List result = session.createCriteria(Emp.class)
.add(Expression.lt("emp_no", empno)
/*emp_no < empno*/
.add(Order.desc(emp_sal))
.list();
Conclusion
About the Author