You are on page 1of 9

HIBERNATE

Hibernate in Working

HQL, CRITERIA AND SQL


Hibernate query, criteria, native queries

Hibernate Query Language


Queries are the most interesting part of writing good data

access code Hibernates powerful query facilities allow you to express almost everything you commonly needed to express in SQL, but in object-oriented terms-using classes and properties of classes There are three ways to express queries in hibernate HQL, Criteria API and direct SQL

Steps involved in running a query


A query must be prepared in the application code before

execution. It involves several distinct steps Step 1: Create a query Step2: Bind runtime arguments to query parameters Step3: Execute the prepared query against the database and retrieve data

Step 1: Creating a query


The org.hibernate,Query and org.hibernate.Criteria interfaces

to be used To create a new Hibernate Query instance, call either createQuery() or createSQLQuery() on a Session.
Query hqlQuery = session.createQuery(from User); Query sqlQuery = session.createSQLQuery(select * from USERS )

Criteria crit = session.createCriteria(User.class);

The criteria instance may be used in the same way as Query-

but also used to construct the object-oriented representation of the query

Step 2: Binding parameters


There are two approaches to parameter binding: using

positional or using named parameters. Both are supported


String queryString = from Item item where item.description like :search;

Query q = session.createQuery(queryString) .setString(search, searchString);


Often youll need multiple parameters

Step 3: Executing a query


Once the Query is created, it can be executed and result can

be retrieved in memory. Retrieving the whole result into memory is very common; called as listing
List result = myQuery.list();
Sometimes you know that the result is only a single instance. Then

you may execute the query with the uniqueResult() method


Bid maxBid = (Bid) session.createQuery(from Bid b order by b.amount desc) .setMaxResults(1) .uniqueResult();

Running native SQL


Hibernate supports execution of native SQL and can

handle resultset of your native SQL query

List result = session.createSQLQuery(select * from CATEGORY) .addEntity(Category.class) .list();

Exercise
Using HQL, retrieve all the Employee objects which you

saved in the database. Using HQL, retrieve all the Employee objects whose name starts with A

You might also like