You are on page 1of 27

Hibernate-Query & Criteria

Copyright 2010 Purple Desk All Rights Reserved. PurpleDesk.and its logo are Trademarks of Purple Desk.www.javafasttrack.com

Query
Query is an interface that provides object oriented representation of a Hibernate
Query. An instance of Query can be obtained by calling the createQuery()
method of the Session class. Queries are executed by calling the list(), scroll()
or iterate() method. The following creates a Query for selection of all orders
from the Order table:
Query query=session.createQuery(from Order);

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Categories of Queries
Hibernate provides three categories of Queries. These are:
1. Hibernate Query Language
2. Query By Criteria
3. Query By Example
Though all of these work on objects and return objects, the second type is more
aimed towards the Object Oriented paradigm. The reason for this is in the
details below.

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Hibernate Query Language


Also known as HQL, this is an object oriented dialect similar to the relational
dialect of SQL. It works on persistent objects. It looks similar to EJB Query
Language or EJBQL. The major difference is that EJBQL (in its version 2.0)
supports only the Retrieve operation of CRUD quad, whereas using HQL all of
these operations can be done. The HQL query goes into the createQuery()
method of session as a string parameter. The main functionalities provided by
HQL include:
Application of restrictions on the properties of associated objects held
together by reference or held in collection.
The ability to order the results. Ordering means retrieving in ascending
or descending order.

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Applying pagination on the result retrieved.


For example the following query retrieves all the orders:
Query q = session.createQuery("from Order");
List result = q.list();
The list() method return an instance of List containing the objects of
Order. It is clear from the above example that the HQL query is similar
to that of SQL. Hence understanding and using it is quite easy.

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Query by Criteria
Known also as QBC, this is the totally object oriented representation of the
SQL Query. In this case, no query comes into the picture. The query is
created internally. The developer works in an object oriented way. The
restrictions are placed using filters, which are nothing but methods of the
Criterion class. The criteria is passed as a parameter which has to be an
instance of the Expression class. The following example will make this more
clear:
Criteria criteria = session.createCriteria(Order.class);
criteria.add( Expression.eq("id", "I009") );
List result = criteria.list();
The first visible difference is the way an instance of Criteria is obtained.
Instead of Query, the name of the class on which the query has to be
executed is provided. Then a Criterion is added using the add() method of the
Criteria class. The parameter is the eq() method of Expression class. The last
part is the same as that of HQL.
Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Query by Example
The long form of QBE, it is not much different from QBC. The difference is that
QBC works on the restrictions representing the where clause, whereas QBE
works with only the example part of the restriction. The example part is
popularly known as the like condition, such as like I% to search for a value
starting with I. The main idea behind QBE is that the application provides an
instance of the class to be queried, with the value of a property set to any
default value. The query when executed returns all the objects with matching
property value. For example,
User exampleUser = new User();
exampleUser.setFirstname("Max");
Criteria criteria = session.createCriteria(User.class);
criteria.add( Example.create(exampleUser) );
List result = criteria.list();

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.someorg.persist.Order;
// use as
// java test. FindOrderById name
public class FindOrderById {
public static void main(String[] args) throws Exception {
// query to issue
String query =
"select order from Order "
+ "where order.id=:id";
// search for what?
String name = args[0];
// init
Configuration cfg = new Configuration()
.addClass(Order.class);
SessionFactory sf = cfg.buildSessionFactory();

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

// open session
Session sess = sf.openSession();
// search and return
List list = sess.find(query, id,
Hibernate.STRING);
if (list.size() == 0) {
System.out.println("No Order having id "
+ name);
System.exit(0);
}
Order o = (Order) list.get(0);
sess.close();
System.out.println("Found Order: " + p);
}
}

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

code rewritten using HQL


import java.util.List;
//other imports
// use as
// java test. FindOrderById name
public class FindOrderById {
public static void main(String[] args) throws Exception {
// query to issue
String query =
"select order from Order "
+ "where order.id=:id";
// search for what?
String name = args[0];
// init
Configuration cfg = new Configuration()
.addClass(Order.class);
SessionFactory sf = cfg.buildSessionFactory();
// open session
Session sess = sf.openSession();

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

// search and return


Query q = session.createQuery("from Order order where+
+order.id=:id");
q.setString(id,name);
List result = q.list();
if (list.size() == 0) {
System.out.println("No Order having id "
+ name);
System.exit(0);
}
Order o = (Order) list.get(0);
sess.close();
System.out.println("Found Order: " + p);
}
}

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Code in QBC
import java.util.List;
//other imports
// use as
// java test. FindOrderById name
public class FindOrderById {
public static void main(String[] args) throws Exception {
// query to issue
String query =
"select order from Order "
+ "where order.id=:id";
// search for what?
String name = args[0];
// init
Configuration cfg = new Configuration()
.addClass(Order.class);
SessionFactory sf = cfg.buildSessionFactory();
// open session
Session sess = sf.openSession();

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

// search and return


Criteria criteria = session.createCriteria(Order.class);
criteria.add( Expression.eq("id", name) );
List result = criteria.list();
if (list.size() == 0) {
System.out.println("No Order having id "
+ name);
System.exit(0);
}
Order o = (Order) list.get(0);
sess.close();
System.out.println("Found Order: " + p);
}
}

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Code by QBE
import java.util.List;
//other imports
// use as
// java test. FindOrderById name
public class FindOrderById {
public static void main(String[] args) throws Exception {
// query to issue
String query =
"select order from Order "
+ "where order.id=:id";
// search for what?
String name = args[0];
// init
Configuration cfg = new Configuration()
.addClass(Order.class);
SessionFactory sf = cfg.buildSessionFactory();
// open session
Session sess = sf.openSession();

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

// search and return


Order exampleOrder = new Order();
exampleOrder.setDate(new Date(1999,10,12);
Criteria criteria = session.createCriteria(Order.class);
criteria.add( Example.create(exampleOrder) );
List result = criteria.list();
if (list.size() == 0) {
System.out.println("No Order having Date "
+ name);
System.exit(0);
}
Order o = (Order) list.get(0);
sess.close();
System.out.println("Found Order: " + p);
}
}

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

What is HQL
HQL is an object-oriented equivalent of SQL
In itself, SQL is very powerful. So when the power of SQL is combined with
the flexibility of the object oriented approach, what we get is Hibernate Query
Language, or HQL for short.

Just like SQL, HQL also provides Projection queries, Aggregation functions,
Grouping and Restrictions. Even the most complex queries in SQL can be
mapped to HQL.

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

will return all the persistent objects containing the first name Max.
That brings us to the end of this section. Each of these will be discussed in detail
in the coming parts. In the next section I will be using the application
developed in the previous tutorial to provide the real world use of all the three
types.

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Query q1 = s.createQuery("from Employee");


List employees1 = q1.list();
System.out.println(employees1);
Query q2 = s.createQuery("select e.empname,e.empemail from Employee e");
List employees2 = q2.list();
for(Object o:employees2){
System.out.println(o);
}

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

HQL categories
HQL functions can be classified into four categories:
1. Projection
2. Restriction
3. Aggregation
4. Grouping

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Projection Projection lets one specify which objects or


properties of objects must be retrieved. In HQL, this can be
done with the help of the from clause and the select clause.

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Restriction
Projection retrieves all the values. But we don't need to do this all
the time. This is where restriction comes into play. The where
clause performs the restriction operation on the rows. The
syntax is similar to that of the SQL where clause.

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Aggregation
There are situations where the retrieved value is based on a
group of values of a column. Average, sum, count of rows, etc.
all come under the aggregation. HQL supports the following
aggregate functions:
a. avg(), sum()

b. min(), max()
b. count(*), count(), count(distinct ), count(all )

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Grouping
Grouping operates on a set of rows. It groups the dataset
according to a specified column/attribute. To group the
resultset/dataset/list according to a column, the group by clause
is used.

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Using HQL

public Order getOrder(String lower, String upper){


Session sess = sf.openSession();
String query = "select o from o "
+ "Order as o join o.products as p "
+ "where o.priceTotal > :priceTotalLower"
+ "and o.priceTotal< :priceTotalUpper";
Query q = sess.createQuery(query);
q.setDouble("priceTotalLower",
Double.parseDouble(lower));
q.setDouble("priceTotalUpper",
Double.parseDouble(upper));
List list = q.list();
Order o=(Order)list.iterator.next();
return o;

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Proj:Aug16new
WS:hibernatedemo

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

<query name="hql_getemployee">
<![CDATA[from com.jft.mapping.Employee where empid =
:empid]]>
</query>

Query query = s.getNamedQuery("hql_getemployee")


.setString("empid", "1");
List l = query.list();
System.out.println(l);

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

Points to Remember
There are some points to be kept in mind when working with HQL. They are as follows:
1. Queries are case insensitive, barring the Java class and properties names. Hence SELECT and
select are the same, but Order and order are not.
2. If the class or package does not find a place in imports, then the objects have to be called with the
package name. For example, if com.someorg.persist.Order is not imported, then the query would be
from
com.someorg.persist.Order and so on.
3. A query like
from Foo foo where foo.bar.baz.customer.address.city is
not null
would translate into a SQL query with four joins. So such queries should be used when absolutely
necessary, as joins cost heavily in terms of memory and processing.

Copyright 2010 Purple Desk All Rights Reserved. www.javafasttrack.com

You might also like