Hibernate

Hibernate Query Language(HQL)
Previous Home Next

It is an object based version of SQL, it is used by hibernate to fetch data. Hibernate even provide a criterion API that provide a type safe and object oriented way to retrieve object from database.Using SQL has following shortcoming:

  1. SQL is standarized but it is vendor -dependent features.
  2. SQL is designed more specifically to work with relational database tables but not object.

To overcome these issues Hibernate introduce its own object oriented query language called Hibernate Query Language(HQL).

Advantages Of Using HQL

  1. HQL queries are database independent.
  2. HQL provide a support for ordering the result persist objects.
  3. HQL is more object oriented which makes us write more easily than Sql.
  4. HQL support pagination.

We know that the Hibernate is a query based language which is work on objects. So we can say that the hibernate is the object oriented language. It works on the table and column. We can say that it works with the persistent objects and their properties. In Hibernate we translate the SQL Query which works to perform the action on the database.

We can use SQL statements directly with hibernate using Native SQL but we always use the HQL Query with database. It gives us the advantes of Hibernate SQL generation and caching strategies. We always remember that in SQL SELECT,FROM,WHERE keyword are not case sensitive but properties like table and column names are case sensitive in HQL. We divided into some basic category to the SQL properties which we use. So here we will discuss that how we need to use?

 

Form

We use FROM when we want to fetch table from the database. In hibernate we can say that we use this when we want to load a complete persistent objects into memory.

With the help of the following syntex we can understand what is the mean of tha above line:


String hql = "FROM Hibernate_HQL";
Query query = session.createQuery(hql);
List results = query.list();

When we use a class thorough a package then we need to fully qualify a class name in HQL, just specify the package and class name as follows:

String hql = "FROM com.hibernatebook.criteria.Hibernate_HQL";
Query query = session.createQuery(hql);
List results = query.list();

As

The AS performed common access in SQL. But in the HQL it can be used to assign aliases to the classes in HQL queries, it uses when you have long queries. For instance, our previous simple example would be the following:


               String hql = "FROM Hibernate_HQL AS HQ";
               Query query = session.createQuery(hql);
               List results = query.list();

               The AS keyword is optional and you can also specify the alias directly after the class name, as follows:

               String hql = "FROM Hibernate_HQL HQ";
               Query query = session.createQuery(hql);
               List results = query.list();

SELECT

The SELECT clause provides more control over the result set than the from clause. If you want to obtain few properties of objects instead of the complete object, use the SELECT clause. Following is the simple syntax of using SELECT clause to get just first_name field of the Employee object:


String hql = "SELECT HQ.firstName FROM Hibernate_HQL HQ";
Query query = session.createQuery(hql);
List results = query.list();

It is notable here that Hibernate_HQL.firstName is a property of Hibernate_HQL object rather than a field of the Hibernate_HQL table.

Where

If you want to narrow the specific objects that are returned from storage, you use the WHERE clause.

Following is the simple syntax of using WHERE clause:


String hql = "FROM Hibernate_HQL HQ WHERE HQ.id = 10";
Query query = session.createQuery(hql);
List results = query.list();

Order By

To sort your HQL query's results, you will need to use the ORDER BY clause. You can order the results by any property on the objects in the result set either ascending (ASC) or descending (DESC). Following is the simple syntax of using ORDER BY clause:


String hql = "FROM Hibernate_HQL HQ WHERE HQ.id > 10 ORDER BY HQ.salary DESC";
Query query = session.createQuery(hql);
List results = query.list();

If you wanted to sort by more than one property, you would just add the additional properties to the end of the order by clause, separated by commas as follows:


String hql = "FROM Hibernate_HQL HQ WHERE HQ.id > 10 " + "ORDER BY HQ.firstName DESC, HQ.salary DESC ";
Query query = session.createQuery(hql);
List results = query.list();

String hql = "FROM Hibernate_HQL HQ WHERE HQ.id > 10 " + "ORDER BY HQ.firstName DESC, HQ.salary DESC "; Query query = session.createQuery(hql); List results = query.list();
Group By

This clause lets Hibernate pull information from the database and group it based on a value of an attribute and, typically, use the result to include an aggregate value. Following is the simple syntax of using GROUP BY clause:

Using Named

Hibernate supports named parameters in its HQL queries. This makes writing HQL queries that accept input from the user easy and you do not have to defend against SQL injection attacks.

Following is the simple syntax of using named parameters:


 String hql = "FROM Hibernate_HQL HQ WHERE HQ.id = : Hibernate_HQL_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id",10);
List results = query.list();

Update

Bulk updates are new to HQL with Hibernate 3, and deletes work differently in Hibernate 3 than they did in Hibernate 2. The Query interface now contains a method called executeUpdate() for executing HQL UPDATE or DELETE statements.

The UPDATE clause can be used to update one or more properties of an one or more objects. Following is the simple syntax of using UPDATE clause:


String hql = "UPDATE Hibernate_HQL set salary = : salary "  + "WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("salary", 1000);
query.setParameter("Hibernate_HQL_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

Delete

The DELETE clause can be used to delete one or more objects. Following is the simple syntax of using DELETE clause:


String hql = "DELETE FROM Hibernate_HQL "  + "WHERE id = : Hibernate_HQL_id";
Query query = session.createQuery(hql);
query.setParameter("Hibernate_HQL_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

Insert Into

HQL supports INSERT clause only where records can be inserted from one object to another object. Following is the simple syntax of using INSERT INTO clause:


String hql = "INSERT INTO Employee(firstName, lastName, salary)"  + "SELECT firstName, lastName, salary FROM old_employee_Hibernate_HQL";
Query query = session.createQuery(hql);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

Aggregate Methods

HQL supports a range of aggregate methods, similar to SQL. They work the same way in HQL as in SQL and following is the list of the available functions:

FunctionsDescription
avg(property name) The average of a property's value
count(property name or *) The number of times a property occurs in the results
max(property name) The maximum value of the property values
min(property name) The minimum value of the property values
sum(property name) The sum total of the property values

The distinct keyword only counts the unique values in the row set. The following query will return only unique count:


String hql = "SELECT count(distinct E.firstName) FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();

Pagination using Query

There are two methods of the Query interface for pagination.

MethodDescription
Query setFirstResult(int startPosition) This method takes an integer that represents the first row in your result set, starting with row 0.
Query setMaxResults(int maxResult) This method tells Hibernate to retrieve a fixed number maxResults of objects.

Using above two methods together, we can construct a paging component in our web or Swing application. Following is the example which you can extend to fetch 10 rows at a time:


String hql = "FROM Employee";
Query query = session.createQuery(hql);
query.setFirstResult(1);
query.setMaxResults(10);
List results = query.list();

Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: