Using Hibernate’s HQL

Hibernate uses a powerful query language called as HQL that is similar to SQL. Compared with SQL, however, HQL is fully object-oriented and understands notions like inheritance, polymorphism and association. Hibernate generates the SQL from these HQL’s and executes against the RDBMS. HQL supports Clauses, Aggregate functions and Subqueries with it’s syntax. Other advantage of using HQL is, it can give us the results as Objects. And the queries written in HQL can be executed in all the databases with out the changing it, so it makes our application most of the time independent of database flavor we choose.We’ll discuss about the clauses and the examples of Clauses.
Clauses in HQL
HQL supports five types of Clauses, they are

  • from Clause
  • where Clause
  • select Clause
  • order by Clause
  • group by Clause
We’ll look at the from clause. And for all of these operation we’ll take the Singer domain class which we have used it in our previous post Simple CRUD Operation Using Hibernate. We have two properties to a Singer which is ID and the Singer Name. We’ll take a closer look at the CRUDTest.listSinger() method, we were using the “from Clause” to select the result from Singer table. We’ll modify that slightly to use the Query to use the from clause. So i’ll be updating listerSinger() method as follows.
			public void listSinger() {
				Session session = FactoryUtil.getSessionFactory().openSession();
				Transaction transaction = null;
				try {
						transaction = session.beginTransaction();
						Query qry = session.createQuery("from Singer singer");
						for (Iterator iterator = qry.iterate(); iterator.hasNext();) {
							Singer singer = (Singer) iterator.next();
							System.out.println(singer.getSingerName());
						}
				}
				catch (HibernateException e) {
					transaction.rollback();
					e.printStackTrace();
				}
				finally {
					session.close();
				}
			}
			
Now, We’ll look at the where clause. The where clause is smilar to where clause in SQL. In HQL Where clause allows us to set the parameters, Compound Path expressions. In case of HQL, the Compound path expressions are making it more useful and easy for the developers too. Consider our Singer example and we are going to add, Event table to store his stage events.This events may have one more attribute called address of the events, which can be put into an other table called address. Now consider the situation of getting all the events performed by a singer, which of the city Bangalore. if some one is asking to get the details of all the singer’s name then i’ll be writing the following query in SQL.
			SELECT sing.singer_name FROM SINGER sing LEFT OUTER JOIN SINGER_EVENTS eve ON eve.singer_id = sing.singer_id LEFT OUTER JOIN EVENT_ADDRESS addr ON addr.event_id = eve.event_id WHERE addr.city = 'Bangalore'
		
Writing these kind of queries is not so easy always and as java developer we won’t be concentrating on writing queries. So HQL provides a easy way to address this using Compound Path Expressions. I can rewrite the above SQL as following using HQL.
		SELECT sing.singer_name FROM SINGER sing WHERE sing.eve.addr.city = 'Bangalore'
	
isn’t that looks easy for us? The other good example i can look at here is, binding the javabean properties directly to HQL’s. This is almost similar to our Prepared Statements in JDBC. Look at the following code snipet,
				Singer singer = (Singer) session.get(Singer.class, singerId);
				singer.setSingerName("Jerry");
				query = session.createQuery(" from Singer sing where sing.name=:singername ");
				query.setProperties(singer);
	
The above code is self explantory, where we set the singer name property using the setProperties() method from Query. We’ll be able to set multiple parameters to it. I suppose this will be really helpful when work with “Dependency Injection”, i.e Inject these values through Spring Config file and call these queries.
The next clause we’ll take it here is, Select Clause. HQL offers may functionalities like SQL queries, We have Aggregate functions, expressions. The most important thing i feel like discussing here is, returning the results as objects, lists and sometimes it can be ad DTO’s also. We’ll consider the above example of getting singer’s who has performed some events in “Banglore”. We’ll add some more parameters to return. We’ll add Event Name and the place of the event to return. We’ll update the CRUDTest.listSinger() to the following,
			public void listSinger() {
				Session session = FactoryUtil.getSessionFactory().openSession();
				Transaction transaction = null;
				try {
						transaction = session.beginTransaction();
						List singerDetails = session.createQuery("select new list(singer.singer_name,eve.event_name) from Singer singer where singer.eve.addr.city='Bangalore' ").list();
						for (Iterator iterator = List.iterator(); iterator.hasNext();) {
							List tempDetail = (List) iterator.next();
							System.out.println(tempDetail.get(0));
						}
				}
				catch (HibernateException e) {
					transaction.rollback();
					e.printStackTrace();
				}
				finally {
					session.close();
				}
			}
			
Basically this returns the list where we have the Singer name and event name. HQL allows us to use the “new” opertor combined with domain objects also. Say for example instead of returning as list, if we may wanted to return as domain object then the code looks like the following,
			public void listSinger() {
				Session session = FactoryUtil.getSessionFactory().openSession();
				Transaction transaction = null;
				try {
						transaction = session.beginTransaction();
						List singerDetails = session.createQuery("select new Singer(singer.singer_name,eve.event_name) from Singer singer where singer.eve.addr.city='Bangalore' ").list();
						for (Iterator iterator = List.iterator(); iterator.hasNext();) {
							Singer tempDetail = (Singer) iterator.next();
							System.out.println(tempDetail.getSingerName());
						}
				}
				catch (HibernateException e) {
					transaction.rollback();
					e.printStackTrace();
				}
				finally {
					session.close();
				}
			}
			
On the same way we use the map also to return the results from DB. For Order by clause and Group by Clause HQL will looks similar to SQL.
Warning
To execute the above code we may need to do a lot of change with the Singer.hbm.xml to accomadate the one-many relationship between Singer and the events. A best alternate could be, we can remove the join tables and return only the singer details.
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Tags: , , , ,

Leave a Reply

Name and Email Address are required fields. Your email will not be published or shared with third parties.

Get Adobe Flash player