Professional Documents
Culture Documents
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);
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.
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();
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();
// 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);
}
}
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();
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();
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.
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.
HQL categories
HQL functions can be classified into four categories:
1. Projection
2. Restriction
3. Aggregation
4. Grouping
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.
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 )
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.
Using HQL
Proj:Aug16new
WS:hibernatedemo
<query name="hql_getemployee">
<![CDATA[from com.jft.mapping.Employee where empid =
:empid]]>
</query>
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.