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 [Link],Query and [Link] interfaces
to be used To create a new Hibernate Query instance, call either createQuery() or createSQLQuery() on a Session.
Query hqlQuery = [Link](from User); Query sqlQuery = [Link](select * from USERS )
Criteria crit = [Link]([Link]);
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 [Link] like :search;
Query q = [Link](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 = [Link]();
Sometimes you know that the result is only a single instance. Then
you may execute the query with the uniqueResult() method
Bid maxBid = (Bid) [Link](from Bid b order by [Link] desc) .setMaxResults(1) .uniqueResult();
Running native SQL
Hibernate supports execution of native SQL and can
handle resultset of your native SQL query
List result = [Link](select * from CATEGORY) .addEntity([Link]) .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